2016-03-01 38 views
3

我自教自己Python出书,而且我在这部分练习的第二部分遇到了麻烦。初学者Python - 如何使用函数修改列表

演习的第1部分: 让魔术师的名字的列表。将列表传递给名为show_magicians()的函数,该函数在列表中打印每个魔术师的名字。

我能没有问题做这部分

我对第1部分代码:

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

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


show_magicians() 

演习的第二部分: 开始复制练习8-9中的程序。写一个名为make_great()的函数,通过在每个魔术师的名字中添加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功能想到的,但没有任何代码工作。任何想法或例子将不胜感激。

+3

你能告诉你有什么到目前为止已经试过你的'make_great'方法? – idjaw

+3

您尚未正确完成第1部分。也许正确的做法会有所帮助:练习告诉你*通过*列表。您目前只是访问全球定义的'magicians_names'列表。 – Shawn

+1

和一点点额外的细节,我想你'show_musicians'应该被称为''show_magicians – idjaw

回答

1

列表中的每个项目都有一个从零开始的关联索引。

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

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

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

所以,你需要做的是循环正如你可能知道,你可以使用这些索引访问列表中的项目通过列表及其索引,随时修改。这正是枚举函数的用途。

>>> 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

谢谢詹姆斯欣赏答案。但是这种方法进入事物的书还没有覆盖,所以我不认为这是我应该去了解它,即使它不产生所需的输出 – iriejams

+0

也许这本书认为你应该创建一个柜台的方式,将其设置为0,使用计数器作为列表索引遍历列表,并随着时间递增。但这不是用Python来完成的最好方法。 –

+0

嗯,我不知道这涉及到,因为这本书还没有涵盖任何有关。我注意到,初学者的书籍往往给那些不完全是最有效的教学特定的概念,后来建立在这些概念的缘故例子来告诉你如何能更有效地实现同样的事情 – iriejams

0

希望这会有所帮助。 [:]通过在要调用的函数中使用原始列表的副本或片来保留原始列表。本书中的练习是第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) 
-1

冗余代码,仍然不使用枚举 - 这是更清洁的方式。

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'] 
+1

因为你滴'枚举',现在的复杂性为O(n^2),而不是为O(n)(假设合并字符串为O(n),这是CPython的实现) –

+0

是场外。我在想锻炼将是熟悉列表用法比性能分析。 –

0

TL; DR

简单(尽管不是那么漂亮)溶液中,用rangelen

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

ACTUAL ANSWER

对于这个多种解决方案,我看到两个能很容易:通过您的列表索引

  1. 运行,也就是说在相同长度的range作为magicians_names

    • 您可以访问元素数量i在列表lstlst[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] + ' !' 
  • 的另一种方式是使用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上找到许多其他链接。