TL;DR
最简单(虽然不是很漂亮)的解决方案,使用range 和len:
def make_great():
for i in range(len(magicians_names)):
magicians_names[i] = 'The Great ' + magicians_names[i] + ' !'
实际答案
有多种解决方案,我看到两个很简单:
-
遍历列表的索引,即与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] + ' !'
- 另一种方法是使用
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 上找到许多其他链接。