2016-08-31 26 views
0

我想使用列表理解從列表中刪除一些項目,只保留那些未指定的項目。使用列表理解保持不在第二個列表中的項目

例如,如果我有2所列出a = [1,3,5,7,10]b = [2,4]我想保持從a不在對應於若干b指數的所有項目。

現在,我試圖使用y = [a[x] for x not in b]但這會產生一個SyntaxError。

y = [a[x] for x in b]工作正常,並保持我想要刪除的元素。

那麼我該如何實現呢?並在一個側面說明,這是一個好辦法,或者我應該使用del

+5

你說這個? '[x for i,x in enumerate(a)if I not in b]' – khelwood

+0

and yes,it is,and no,you not not;) – georg

+0

'in'是list comprehension語法的一部分,而不是'在'運算符中,所以不能簡單地用'不在'中替換。 – chepner

回答

6

您可以使用enumerate()和查找索引中b

>>> a = [1, 3, 5, 7, 10] 
>>> b = [2, 4] 
>>> [item for index, item in enumerate(a) if index not in b] 
[1, 3, 7] 

需要注意的是,提高查找時間,最好有b作爲設置而不是列表。 Lookups into sets are O(1) on average而在列表中 - O(n)其中n是列表的長度。

-1

在此之後:

y = [a[x] for x in b] 

只需添加:

for x in y: 
    a.remove(x) 

,那麼你最終有一個剝離下來列表中

+1

'remove'刪除元素的第一次出現,不一定是您想要刪除的元素。 – chepner

1

猜你正在尋找類似的財產以後:

[ x for x in a if a.index(x) not in b ] 

或者,使用過濾器:

filter(lambda x : a.index(x) not in b , a) 
0

試試這個它會工作

[j for i,j in enumerate(a) if i not in b ] 
相關問題