【问题标题】:Beginner Python - How to modify a list using a function初学者 Python - 如何使用函数修改列表
【发布时间】:2016-06-13 06:42:32
【问题描述】:

我正在从一本书中自学 Python,但我在这个 2 部分练习的第二部分遇到了问题。

练习的第一部分: 列出魔术师的名字。将列表传递给名为 show_magicians() 的函数,该函数会打印列表中每个魔术师的姓名。

我能够毫无问题地完成这部分

我的第一部分代码:

magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']

def show_magicians():
    for name in magicians_names:
        print(name)


show_magicians()

练习的第二部分: 从练习 8-9 中的程序副本开始。编写一个名为 make_great() 的函数,通过在每个魔术师的名字中添加短语 the Great 来修改魔术师列表。调用 show_magicians() 来查看列表实际上已经被修改了。

我的第二部分代码

magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']

def show_magicians():
    for name in magicians_names:
        print(name)

def make_great():


show_magicians()

我已经尝试了几乎所有我能想到的关于 make_great 函数的想法,但到目前为止没有任何效果。任何想法或示例将不胜感激。

【问题讨论】:

  • 您能否展示一下您迄今为止为您的make_great 方法所做的尝试?
  • 您还没有正确完成第 1 部分。也许以正确的方式做会有所帮助:练习告诉你通过列表。您目前只是访问全局定义的列表magicians_names
  • 还有一点额外的细节,我认为你的show_musicians应该被称为show_magicians
  • @Shawn hmmm 好的,让我考虑一下
  • @idjaw 很好看...只是确保你在关注大声笑

标签: python list function


【解决方案1】:

这个问题来自 Python Crash Course 书的第 150 页。有几种方法可以做到,但我认为他们希望您使用第 142 页中介绍的 Return:

def make_great(magician_names):
    current_name = []
    for name in magician_names:
        current_name.append("The Great " + name.title())
    return current_name

magician_names = ['merlin', 'gandalf',  'saruman']

great_magician = make_great(magician_names)
print(great_magician)   

【讨论】:

    【解决方案2】:

    TL;DR

    最简单(虽然不是很漂亮)的解决方案,使用rangelen

    def make_great():
        for i in range(len(magicians_names)):
            magicians_names[i] = 'The Great ' + magicians_names[i] + ' !'
    

    实际答案

    有多种解决方案,我看到两个很简单:

    1. 遍历列表的索引,即与magicians_names 长度相同的range

      • 您可以使用lst[i] 访问列表lst 中的元素编号i
      • range(n) 生成一个列表:[0, 1, 2, ..., n-1]
      • len 是一个函数,它给出了一个列表的长度(或者很多东西的长度,但我们感兴趣的是列表)

    这给出了:

    def make_great():
        # len(magician_names) is 4, and range(4) is [0, 1, 2, 3]
        for i in range(len(magicians_names)):
            # update the content of the list like this
            magicians_names[i] = 'The Great ' + magicians_names[i] + ' !'
    
    1. 另一种方法是使用enumerate 函数,该函数将为列表中的每个元素提供一个类似(index, element) 的元组。

    像这样:

    def make_great():
        # enumerate(magician_names) is [(0, 'Marv'), (1, 'Wowzo'), ...]
        for i, name in enumerate(magicians_names):
            # update the content of the list like this
            magicians_names[i] = 'The Great ' + name + ' !'
    

    第二种方式被认为更优雅一些,尽管它们都有效。要对其进行测试,请先运行make_great(),以修改列表。然后运行show_magicians()

    >>> make_great()
    >>> show_magicians()
    The Great Marv !
    The Great Wowzo !
    The Great Trickster !
    The Great Didlo !
    

    其他信息

    这实际上修改了列表magicians_names,您将来可能不希望这样做。您可以在列表的副本上运行该函数。要创建列表的副本,您可以使用[:],这意味着所有元素来自

    copy_of_mn = magicians_names  # does not copy : if you modify one, you modify the other
    copy_of_mn = magicians_names[:]  # does copy : the two are the sames, but independent
    

    如果你想获得这个列表,你可以这样做(创建一个副本并修改它),或者使用append 到一个空列表。

    def make_great():
        # create an empty list
        result = []
        # we don't even need 'enumerate' anymore
        for name in magicians_names:
            # 'this.append(that)' means 'add that at the end of this'
            result.append('The Great ' + name + ' !')
        # return the list (if you omit this line, the function will return 'None')
        return result
    

    使用此解决方案,函数返回一个包含所有修改名称的列表:['The Great Marv !', 'The Great Wowzo !', 'The Great Trickster !', 'The Great Didlo !']

    稍后对show_magicians进行小修改,可以打印出来!

    def show_magicians(list_of_names):
        for name in list_of_names:
            print(name)
    

    然后只需调用show_names(make_great(magicians_names)),因为make_great(magicians_names) 将创建所有修改名称的列表,show_names(something) 打印something 的所有元素。

    您可能还希望能够将您的方法与其他列表和其他要添加的内容重用。这个想法是为您的函数使用参数,如最后一段代码中所述:

    def add_prefix_and_suffix(list_of_names, prefix, suffix):
        for i, name in enumerate(list_of_names):
            # alter the list_of_names, adding prefix and suffix to the name
            list_of_names[i] = prefix + name + suffix
    

    那么您可以简单地使用add_prefix_and_suffix(magicians_names, 'The Great ', ' !') 而不是make_great。更重要的是,你可以从这个函数中定义make_great

    初学者方式:

    def make_great():
        add_prefix_and_suffix(magicians_names, 'The Great ', ' !')
    

    Lambda 方式:

    make_great = lambda: add_prefix_and_suffix(magicians_names, 'The Great ', ' !')
    

    你的练习可以做很多事情,但我认为现在就足够了。我提供了一些链接作为示例,但如果您愿意,您可以在 Internet 上找到许多其他链接。

    【讨论】:

      【解决方案3】:

      冗余代码,但它仍然不使用枚举——顺便说一句,这更干净。

      magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']
      
      for m in magicians_names:
         magicians_names[magicians_names.index(m)] = "Great "+m
      
      magicians_names
      >> ['Great Marv', 'Great Wowzo', 'Great Trickster', 'Great Didlo']
      

      【讨论】:

      • 是的,偏离路线。我认为练习是熟悉列表用法而不是性能分析。
      【解决方案4】:

      希望这会有所帮助。 [:] 通过制作原始列表的副本或切片以在被调用的函数中使用来保留原始列表。书中的练习是第 150 页的 8-9 到 8-11 Python 速成课程

      def meta_mags(show_mags, great_mags):
          """(Change regular show magicians to Great magicians by moving them 
           to another list using a function meta_mags)"""
          while show_mags:
              change_mags = show_mags.pop()
              # show the change from one list show_mags to great_mags
              print("Great magicians: " + change_mags.title())
              great_mags.append(change_mags)
      
      
      def show_great_mags(great_mags):
          """Print --The Great--- after each great_mags magicians name"""
          for great_mag in great_mags:
              print(great_mag.title() +" The Great will be performing tonight !") 
      
      
      show_mags = ['alice', 'david', 'carolina']
      great_mags = []
      meta_mags(show_mags[:], great_mags)
      show_great_mags(great_mags) 
      print(show_mags)
      

      【讨论】:

        【解决方案5】:

        列表中的每个项目都有一个关联的索引,从零开始。您可能知道,您可以使用这些索引访问列表中的项目:

        >>> magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']
        >>> magicians_names[0]
        'Marv'
        

        您还可以使用这些索引修改列表项:

        >>> magicians_names[0] = 'Jerry Boomfang'
        >>> magicians_names[0]
        'Jerry Boomfang'
        

        因此,您需要做的是遍历列表及其索引,随时进行修改。这正是 enumerate 函数的用途。

        >>> for index, magician in enumerate(magicians_names):
        ...     magicians_names[index] += ' is great!'
        ...
        >>> magicians_names
        ['Jerry Boomfang is great!', 'Wowzo is great!', 'Trickster is great!', 'Didlo is great!']
        

        【讨论】:

        • 感谢詹姆斯感谢您的回答。然而,这种方法正在涉及本书尚未涵盖的内容,所以我认为这不是我应该采用的方式,即使它确实产生了所需的输出
        • 也许本书认为您应该创建一个计数器,将其设置为 0,使用计数器作为列表索引逐步遍历列表,并在执行过程中将其递增。但这不是在 Python 中做到这一点的最佳方式。
        • 嗯,我也不确定它是否涉及这个,因为这本书还没有涉及到任何相关内容。我注意到初学者书籍往往会给出一些例子,但这些例子并不是最有效的,以便教授特定的概念,然后在这些概念的基础上展示如何更有效地实现相同的目标
        猜你喜欢
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2015-07-24
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 2015-09-21
        • 1970-01-01
        相关资源
        最近更新 更多