![](/img/trans.png)
[英]dataclass references the same object rather than initializing a new one
[英]inserting the value in the same list rather than in a new
arr = [-1, -1, 0, 1, 1]
for x in arr:
if x > 0:
list = []
list.append(x)
print(list)
output 是:[1] [1] 但我希望 output 为:[1,1] 我希望它插入从 arr 到列表的每个正值。
您必须在for
循环之前定义您的列表,否则,您的列表将在每次迭代时分配一个空列表
arr = [-1, -1, 0, 1, 1]
my_list = []
for x in arr:
if x > 0:
my_list.append(x)
print(my_list)
output:
[1]
[1, 1]
正如 kederrac 所说,您在每次迭代中都创建一个新的空列表,您必须在循环之外定义列表。
此外,“list”是 Python 中的关键字,永远不要将变量命名为关键字,这是一件很糟糕的事情,即使它现在运行良好。 这种做法终有一天会咬到你。
完成任务的更优雅的方法是使用理解:
arr = [-1, -1, 0, 1, 1]
myList = [e for e in arr if e > 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.