[英]Why is this condition-based list comprehension not working?
我要在刪除所有重復項后從現有列表創建一個列表。 如果我使用“ for循環”,則程序可以運行,但是如果使用列表推導,則什么也不會發生。
#use for loop
l=[1,2,2,3,1,1,2]
j=[]
for i in l:
if i not in j:
j.append(i)
print l
print j
#using list
l1=[1,2,2,3,1,1,2]
j1=[]
j1=[i for i in l1 if i not in j1]
print l1
print j1
j1
開頭是[]
,並且在列表理解的中間點不更新。 可以這樣做,而不是列表理解:
l1=[1,2,2,3,1,1,2]
j1=list(set(l1))
print l1
print j1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.