原始列表在功能中编辑后不会发生更改



我学习Python一周,遇到一个问题。一个列表在功能上进行了编辑。打印参数时,我得到了正确的列表,但原始列表为空。

name_list=['Jack','Lucky','Jimi','Andy']
def show_magicians(list):
for name in list:
print('Magician name is ' + name + '!')
def make_great(list):
new_name_list=[]
while list:
temp_name = list.pop()
new_name_list.append('the Great ' + temp_name)
list = new_name_list[:]
print(list)         # I get correct list.
print(name_list)    # the list is null ??? 

make_great(name_list)
show_magicians(name_list)

当您运行while循环时,它会清空您的列表,这就是为什么它显示为空的原因。在弹出之前,尝试获取列表。

name_list=['Jack','Lucky','Jimi','Andy']
def show_magicians(list):
for name in list:
print('Magician name is ' + name + '!')
def make_great(list):
new_name_list=[]
for name in list:
new_name_list.append('the Great ' +name)
list = new_name_list[:]
print(list)         
print(name_list)  
make_great(name_list)
show_magicians(name_list)  

不删除元素,只需循环遍历每个元素并附加到新列表(new_name_list(

谢谢大家。我得到了答案。参数";列表";与变量"断开连接;name_list"当";list=new_name_list[:]";。所以在";"列表";,但在";name_list";。

请参阅本文,https://nedbatchelder.com/text/names.html

最新更新