Python速成课程Q8-10

时间:2017-01-22 15:56:41

标签: python

8-9。魔术师:列出魔术师的名字。将列表传递给名为show_magicians()的函数,该函数在列表中打印每个魔术师的名称。

8-10。伟大的魔术师:从练习8-9开始,获得你的程序副本。编写一个名为make_great()的函数,通过将短语"the Great"添加到每个魔术师的名字来修改魔术师列表。调用show_magicians()以查看列表实际已被修改。

8-10: 我知道这会奏效:

def make_great(list_of_magicians):
    index = 0
    while index < len(list_of_magicians):
        for magician in list_of_magicians:
            list_of_magicians[index] = "The Great " + magician
            print(list_of_magicians) # Seeing change in list each time.
            index += 1 

**问:为什么这不起作用? **

def make_great(list_of_magicians):
    for magician in list_of_magicians:
        magician = 'The great ' + magician

2 个答案:

答案 0 :(得分:2)

这一行:

table.ex1 {
    table-layout: auto;
    height: 20px;
    overflow-y: scroll;
}

table.ex2 {
    table-layout: fixed;
    height: 20px;
      overflow-y: scroll;

}

仅修改变量magician = 'The great ' + magician 。这对值没有影响 在列表中。

在可行的代码中,相应的行是:

magician

这会更改列表的实际内容,因此可以正常工作。

答案 1 :(得分:1)

for magician in list_of_magicians:
    magician = 'The great ' + magician

第一行迭代list_of_magicians中的字符串,依次将每个字符串绑定到名称magician。它创建字符串的副本。但是,下一行通过将'The great 'magician字符串连接起来创建一个新字符串,然后=将该新字符串绑定到名称magician,并在该操作之后name不再引用列表项。

如果我们可以做str_prepend('The great ', magician),那么你的技术会起作用,但我们不能这样做,因为Python字符串是不可变的。但这是使用列表列表的相关示例。因为列表 可变,我们可以通过修改a来更改u中的列表:

a=[['a'], ['b'], ['c']]
for u in a:
    u.append('z')
print(a)

<强>输出

[['a', 'z'], ['b', 'z'], ['c', 'z']]

这是编写make_great函数的一种方法。在Python中,通常优选直接迭代容器中的项而不是通过索引间接迭代。编写make_great函数的直接方法是执行此操作:

def make_great(list_of_magicians):
    new_list = []
    for magician in list_of_magicians:
        new_list.append('The great ' + magician)
    return new_list

magician_names = ['Alice', 'Alex', 'Blake']
magician_names = make_great(magician_names)
print(magician_names)

<强>输出

['The great Alice', 'The great Alex', 'The great Blake']

这会将原始magician_names列表替换为新列表。如果我们想修改原始列表对象,我们可以使用切片赋值:

magician_names[:] = make_great(magician_names)

或者,我们可以在make_great内进行切片分配,改变传入的列表。 Python函数的常规做法是将其参数改为返回None

def make_great(list_of_magicians):
    new_list = []
    for magician in list_of_magicians:
        new_list.append('The great ' + magician)
    list_of_magicians[:] = new_list

magician_names = ['Alice', 'Alex', 'Blake']
make_great(magician_names)
print(magician_names)

或者我们可以使用列表理解来做几乎相同的事情,它更紧凑(并且更快),并且不需要new_list名称:

def make_great(list_of_magicians):
    list_of_magicians[:] = [
        'The great ' + magician for magician in list_of_magicians
    ]