簡體   English   中英

Python,如果包含匹配的元組,則刪除整個列表

[英]Python, removing whole list if it contains a matching tuple

我希望以前沒有問過這個問題,但是我很難說出我要做什么!

如果我解釋我的輸入和所需的輸出,可能會更容易

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中的手。 因此,需要從l1中刪除條目[(14,'d'),(14,'c')],因為(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!

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)]
[x for x in l1 if not any(y in l2 for y in x)]
    >>> [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')]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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