Python,如果它包含匹配的元组,则删除整个列表

时间:2011-03-22 19:02:03

标签: python list tuples

我希望以前没有问过这个问题,但是我很难说出我正在尝试做的事情!

如果我解释我的输入和所需的输出

,可能会更容易
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,'d'),(14,'c')]需要从l1中删除,因为(14,'c')在l2--即使(14,'d')isn'在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!

3 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:1)

[x for x in l1 if not any(y in l2 for y in x)]

答案 2 :(得分: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')]]