2011-03-22 21 views
1

我希望這之前沒有被問過,但是我很難把我正在嘗試做的事情放在文字中!Python,刪除整個列表,如果它包含匹配的元組

如果我解釋我的輸入,以及所需的輸出

l1 = [[(14, 'h'), (14, 'd')], [(14, 'h'), (14, 'c')], [(14, 'h'), (14, 's')], [(14, 'd'), (14, 'c')], [(14, 'd'), (14, 's')], [(14, 'c'), (14, 's')], [(13, 'h'), (13, 'd')], [(13, 'h'), (13, 'c')], [(13, 'h'), (13, 's')], [(13, 'd'), (13,'c')], [(13, 'd'), (13, 's')], [(13, 'c'), (13, 's')], [(12, 'h'), (12, 'd')], [(12, 'h'), (12, 'c')], [(12, 'h'), (12, 's')], [(12, 'd'), (12, 'c')], [(12, 'd'), (12, 's')], [(12, 'c'), (12, 's')]] 

l2 = [(13,'h'),(13,'d'),(14,'c'),(14,'s'),(14,'h')] 

所以這第一個列表,L1,是列出的清單可能更容易的,每個單子是2張牌撲克手。

基本上我想要做的是,如果一張卡在l2中,需要將l1中的手去掉。 (14,'c')]需要從l1中刪除,因爲(14,'c')在l2中 - 儘管(14,'d')不是' t在l2。

從這個例子所需的輸出應該是,

[[(13, 'c'), (13, 's')], [(12, 'h'), (12, 'd')], [(12, 'h'), (12, 'c')], [(12, 'h'), (12, 's')], [(12, 'd'), (12, 'c')], [(12, 'd'), (12, 's')], [(12, 'c'), (12, 's')]] 

我想過遍歷L1內所有元組和刪除他們,如果他們在L2,再後來回去遍歷在列表l1並刪除任何沒有len == 2.這似乎不是最好的方式去,但。

有什麼想法?

ManyTIA!

+0

出於好奇,爲什麼不能在「卡的使用對象列表「類而不是元組列表的列表? – syrion 2011-03-22 19:04:08

+0

你得問問我繼承的代碼:) – GP89 2011-03-22 19:18:04

回答

5
l2_set = set(l2) 
# or use 
# l2_set = {(13,'h'),(13,'d'),(14,'c'),(14,'s'),(14,'h')} 
# directly 

l1 = [hand for hand in l1 if not (hand[0] in l2_set or hand[1] in l2_set)] 

如果條目可包含≥2的成員,則可以將過濾條件

l1 = [hand for hand in l1 if all(subhand not in l2_set for subhand in hand)] 
+0

謝謝! 這個第一個解決方案也可以在沒有設置的情況下工作 – GP89 2011-03-22 19:19:39

+0

@user:是的,但是一套更適合成員資格測試。 – kennytm 2011-03-22 19:22:56

0
>>> [x for x in l1 if not set(x).intersection(l2)] 
[[(13, 'c'), (13, 's')], [(12, 'h'), (12, 'd')], [(12, 'h'), (12, 'c')], [(12, 'h'), (12, 's')], [(12, 'd'), (12, 'c')], [(12, 'd'), (12, 's')], [(12, 'c'), (12, 's')]] 
1
[x for x in l1 if not any(y in l2 for y in x)] 
相關問題