Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3:如何在函数中更改列表中的单个项_Python_Python 3.x_List_Function - Fatal编程技术网

Python 3:如何在函数中更改列表中的单个项

Python 3:如何在函数中更改列表中的单个项,python,python-3.x,list,function,Python,Python 3.x,List,Function,我创建了一个魔术师名单。我试图将“伟大”添加到列表中的每个项目中,同时永久更改列表格式。以下是我目前的代码: magician_names = ['houdini' , 'chris angel', 'ted'] def show_magicians(): print("These are your magicians tonight.") while magician_names: print(magician_names) break show

我创建了一个魔术师名单。我试图将“伟大”添加到列表中的每个项目中,同时永久更改列表格式。以下是我目前的代码:

magician_names = ['houdini' , 'chris angel', 'ted']
def show_magicians():
    print("These are your magicians tonight.")
    while magician_names:
        print(magician_names)
        break
show_magicians()

def make_great():
    for name in magician_names:
            while True:
                ['The Great' , name]
                break
    print(magician_names)
我可以创建一个for循环和一个字符串来打印每个名字,前面有“Great”,如下所示:

for magician in magician_names:
    print("The Great " + magician)
将打印此结果:

The Great houdini
The Great chris angel
The Great ted
但我希望在调用函数并打印列表“魔术师名称”时,它能打印出一个经过修改的列表版本,格式如下:

['the great houdini' , 'the great chris angel', 'the great ted']

这将给出导出的输出:

magician_names = ['houdini' , 'chris angel', 'ted']
l = ['The Great ' + name for name in magician_names]
print(l)

谢谢你的帮助,我终于得到了。我将此代码放在第二个函数中,当两个函数都被调用时,代码将按需要返回:

for i in range(0, len(magician_names)):
        magician_names[i] = "The Great " + magician_names[i]

不知道你到底在做什么,但你把一个简单的问题复杂化了。列表在python中是可变的数据结构,因此您只需在列表迭代中使用字符串连接。用新字符串替换列表中的每个项目,或用新字符串创建新列表。请花一些时间练习这些示例。它将让您了解Python提供的帮助您解决问题的工具。
而魔术师姓名:print(魔术师姓名)break
有什么意义<代码>打印(魔术师的名字)也是这样做的。我刚刚用代码更新了列表,它就工作了。但每当我尝试在函数中运行它时,它都会返回一个错误:“局部变量:赋值前引用的魔术师名称”。@drewmende我假设该函数中不知道
魔术师名称
,但这只是一个猜测,因为我没有代码。也许您可以尝试将其作为参数传递给函数。