- 的另一种方式是使用
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上找到许多其他链接。
你能告诉你有什么到目前为止已经试过你的'make_great'方法? – idjaw
您尚未正确完成第1部分。也许正确的做法会有所帮助:练习告诉你*通过*列表。您目前只是访问全球定义的'magicians_names'列表。 – Shawn
和一点点额外的细节,我想你'show_musicians'应该被称为''show_magicians – idjaw