【发布时间】:2022-08-21 11:47:22
【问题描述】:
list1 = [2,4,6,8,3,4,2,]
从上面的列表中,我需要获得以下结果
[2,4,6,8]
这是我尝试的方式。但它导致了一个错误而没有给出预期的结果。
list1 = [2,4,6,8,3,4,2,]
x=[]
for num in list1:
if (num % 2 == 0) and (num not in list1):
x.append(num)
print(x)
所以我需要你的帮助才能只选择一次偶数而不重复相同的数字 提前致谢...!
-
(num not in list1)总是False因此and连接总是返回False并且列表永远不会被更新。该条件应替换为... (num not in x):。见 Sumit S Chawla 的回答
标签: python python-3.x list for-loop append