[英]How to append elements into empty list
I am trying to append elements into empty list. 我试图将元素追加到空列表中。 using list.append() method.
使用list.append()方法。 script gives recent value, But not appending to list.
脚本给出最近的值,但不追加到列表中。
I have tried below script it is giving updated value. 我试过下面的脚本,它给了更新的价值。
for i in range(10):
x = []
if i > 1:
x.append(i)
print (x)
Output : [9] 输出:[9]
Expected output : [2, 3, 4, 5, 6, 7, 8, 9] 预期输出:[2、3、4、5、6、7、8、9]
Could you please help me why i am getting this output and how to resolve it? 您能帮我为什么我得到此输出以及如何解决它吗?
You should not create new list in every iteration because it replaces the old data with a new list: 您不应在每次迭代中都创建新列表,因为它会将旧数据替换为新列表:
x = []
for i in range(10):
if i > 1:
x.append(i)
print (x)
However, there is a simpler way to do this: 但是,有一种更简单的方法可以做到这一点:
[i for i in range(10) if i > 1]
Output: 输出:
[2, 3, 4, 5, 6, 7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.