[英]Can't figure out how to modify list items in function in Python?
When I call show_magicians, their names are printed, but I want, when I call make_great, have their name + the Great added. 当我打电话给show_magicians时,会打印他们的名字,但是当我打电话给make_great时,我想给他们加上名字+伟大。
def make_great(magician_names):
"""Adds the phrase 'the Great' to each magician's name."""
for name in magician_names:
# I want to add 'the Great' to each item in the list
# magician_names so that when I call show_magicians,
# the items in the list will have 'the Great' added
# to them.
def show_magicians(magician_names):
"""Print the names of magicians in a list."""
for name in magician_names:
print(name.title())
magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
make_great(magician_names)
show_magicians(magician_names)
Note the for name in magician_names won't allow you to change the list value of the name as strings in Python can't be changed in place, you must replace them with a new value. 请注意magician_names中的for名称将不允许您更改名称的列表值,因为无法在Python中更改字符串,必须将其替换为新值。 You'll have to edit the list directly by using magician_names[0]... etc. Here I have returned a new list with the changed names, which is the prefered way to deal with lists passed to methods. 您必须使用magician_names [0] ...等直接编辑列表。在这里,我返回了一个具有更改名称的新列表,这是处理传递给方法的列表的首选方法。
def make_great(magician_names):
"""Adds the phrase 'the Great' to each magician's name."""
return [ name + ' the Great' for name in magician_names]
def show_magicians(magician_names):
"""Print the names of magicians in a list."""
for name in magician_names:
print(name.title())
magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
magician_names = make_great(magician_names)
show_magicians(magician_names)
Here is a method that changes the list directly: 这是一种直接更改列表的方法:
def make_great(magician_names):
"""Adds the phrase 'the Great' to each magician's name."""
for index in range(len(magician_names)):
magician_names[index] += ' the Great'
#!/usr/bin/python
def make_great(magician_names):
"""Adds the phrase 'the Great' to each magician's name."""
for name in magician_names:
print "{} the Great".format(name)
def show_magicians(magician_names):
"""Print the names of magicians in a list."""
for name in magician_names:
print(name.title())
magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
make_great(magician_names)
show_magicians(magician_names)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.