简体   繁体   English

Python列表追加错误

[英]Python list append error

I tried to use append with multiple lists at the same time (in a continual line). 我尝试同时(连续一行)将append与多个列表一起使用。

However, it added all the items to all of my lists. 但是,它将所有项目添加到了我的所有列表中。 Please see the script and result below: 请在下面查看脚本和结果:

x1=y1=z1=[]
for i in range(1,5):
    x1.append(i)
    y1.append(i*4)
    z1.append(i*10)
print ("\n x1=", x1,"\n y1=", y1,"\n z1=", z1)

Result: 结果:

 x1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40] 
 y1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40] 
 z1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40]

Thanks for your comment. 谢谢你的评论。

That's because x1 , x2 and x3 binds to the same list. 这是因为x1x2x3绑定到同一列表。 Write x1, x2, x3 = [], [], [] instead of x1 = x2 = x3 = [] . x1, x2, x3 = [], [], []代替x1 = x2 = x3 = []

This is because all your list variables are pointing to the same list. 这是因为所有列表变量都指向同一列表。

Initialize your lists as follows instead: 初始化列表如下:

x1 = []
y1 = []
z1 = []

Doing, x1 = y1 causes both these variables to point to the same memory space and so modifying one makes it look like you are modifying all of them when in fact they are all just the same thing 这样做,x1 = y1会使这两个变量都指向相同的内存空间,因此修改一个变量就好像您正在修改所有变量,而实际上它们都是一样的东西

If you are only interested in the output, you can do a more pythonic approach using list comprehensions: 如果您只对输出感兴趣,则可以使用列表推导来执行更Python化的方法:

print [i for i in range(1,5)]
print [i*4 for i in range(1,5)]
print [i*10 for i in range(1,5)]

Or if you want to keep the values then do: 或者,如果您想保留这些值,请执行以下操作:

x1 = [i for i in range(1,5)]
y1 = [i*4 for i in range(1,5)]
z1 = [i*10 for i in range(1,5)]
print ("\n x1=", x1,"\n y1=", y1,"\n z1=", z1)

Or if you really want to shrink your code, you could do this: 或者,如果您真的想缩小代码,则可以执行以下操作:

for j in zip(*[[i,i*4,i*10] for i in range(1,5)]): print j

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM