我正在创建一个名为show_magicians()
的函数,它打印出名为magician_names
的列表的内容。
我正在尝试创建一个名为make_great()
的新功能,该功能会将列表magician_names
修改为"The Great [Insert name]"
。
但是我只能打印"The Great Nick"
并且我不确定如何修改此列表,这样当我调用show_magicians
时,该函数将打印出修改后的列表。
例如:
magician_names = ['jim', 'kaitlyn', 'nick', 'paul', 'kyle']
make_great
功能后:
magician_names = ['The Great jim', 'The Great kaitlyn', 'The Great nick', 'The Great paul', 'The Great kyle']
以下是我目前的代码:
def show_magicians(magician_names):
for magician_name in magician_names:
print(magician_name.title())
magician_names = ['jim', 'kaitlyn', 'nick', 'paul', 'kyle']
show_magicians(magician_names)
def make_great(magician_names):
for magician_name in magician_names:
print("The Great " + magician_name)
make_great(magician_names)
答案 0 :(得分:1)
我构造了这样的代码:
def show_magicians(magician_names):
for magician_name in magician_names:
print(magician_name.title())
def make_great(magician_names):
for magician_name in magician_names:
print("The Great " + magician_name)
magician_names = ['jim', 'kaitlyn', 'nick', 'paul', 'kyle']
show_magicians(magician_names)
make_great(magician_names)
<强>输出:强>
Jim
Kaitlyn
Nick
Paul
Kyle
The Great jim
The Great kaitlyn
The Great nick
The Great paul
The Great kyle
我应该指出def make_great(magician_names):
没有创建新列表并返回它,它会将列表作为参数,在这种情况下,magician_names
遍历它并添加短语&#34;伟大的......&#34;。
作者确实得到了他的偏见的答案:https://ehmatthes.github.io/pcc/
我也有这本书,但是,我没有遇到你遇到的问题。
答案 1 :(得分:0)
为什么不使用列表理解而不是函数?:
require "debug"
答案 2 :(得分:0)
你是在正确的轨道,但基本的方法是你的功能1)制作一个空列表; 2)对于传入列表中的每个条目,创建修改后的名称; 3)将修改后的名称添加到您创建的(一次空)列表中。然后传回那个清单。
示例:
def make_great(magician_list):
great_list=[]
for name in magician_list:
newname = "The Great " + name
great_list.append(newname)
return great_list
magician_names = ['jim', 'kaitlyn', 'nick', 'paul', 'kyle']
print magician_names
great_magician_names = make_great(magician_names)
print great_magician_names
答案 3 :(得分:0)
这个怎么样?
magician_names = ['jim', 'kaitlyn', 'nick', 'paul', 'kyle']
print(list(map(lambda x:"The Great {}".format(x),magician_names)))
输出:
['The Great jim', 'The Great kaitlyn', 'The Great nick', 'The Great paul', 'The Great kyle']