簡體   English   中英

為什么這種基於條件的列表理解不起作用?

[英]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

計算表達式[i for i in l1 if i not in j1] ,則[i for i in l1 if i not in j1] ,然后將其賦給j1 因此,在評估期間, j1保持為空。

順便說一句,刪除重復項的一個簡單方法是將列表傳遞給set函數,然后如果需要列表,則傳遞給list函數:

j1=list(set(l1))

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM