Python中的意外列表行为 [英] Unexpected list behavior in Python
问题描述
我想撤消一个列表,但是我设法做到了,但是在工作的中间我发现了一些奇怪的事情.以下程序正常运行,但 list_reversed [i] = list [len(list)-1-i] 和 print(list [i])当然,最后一行)会导致列表中的更改.我没看到什么?我的Python版本是3.3.3.预先谢谢你.
I wanted to reverse a list, and I managed to do so, but in the middle of the work I noticed something strange. The following program works as expected but uncommeting line list_reversed[i]=list[len(list)-1-i] and print(list[i]) (commenting the last line of course) leads to a change in list. What am I not seeing? My Python version is 3.3.3. Thank you in advance.
list=[1,2,3,4,5,6]
list_reversed=list
for i in range(0,len(list)):
#list_reversed[i]=list[len(list)-1-i]
#print(list[i])
print(list[len(list)-1-i])
推荐答案
以下内容:
list_reversed = list
使两个变量引用相同的列表.当您更改一个时,它们都会更改.
makes the two variables refer to the same list. When you change one, they both change.
要复制,请使用
list_reversed = list[:]
最好还是使用内置函数,而不要编写自己的函数:
Better still, use the builtin function instead of writing your own:
list_reversed = reversed(list)
P.S.我建议不要使用list
作为变量名,因为它会掩盖内置.
P.S. I'd recommend against using list
as a variable name, since it shadows the builtin.
这篇关于Python中的意外列表行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!