Python,使用部分匹配测试集合中成员资格的简明方法

时间:2010-04-23 05:35:00

标签: membership collections python

测试是否有一个元组以集合中的另一个元组开头的pythonic方法是什么?实际上,我真的在匹配索引之后,但我可以从测试示例中找出答案

例如:

c = ((0,1),(2,3))
# (0,) should match first element, (3,)should match no element

我应该添加我的python是2.4和/或2.5

感谢

3 个答案:

答案 0 :(得分:3)

编辑: 感谢OP对该问题的补充说明 S.Mark's nested list comprehensions非常邪恶;检查一下。

我可能会选择使用辅助功能:

def tup_cmp(mytup, mytups):
    return any(x for x in mytups if mytup == x[:len(mytup)])

>>> c = ((0, 1, 2, 3), (2, 3, 4, 5))
>>> tup_cmp((0,2),c)
False
>>> tup_cmp((0,1),c)
True
>>> tup_cmp((0,1,2,3),c)
True
>>> tup_cmp((0,1,2),c)
True
>>> tup_cmp((2,3,),c)
True
>>> tup_cmp((2,4,),c)
False

原始答案:
是否使用list-comprehension为您服务?:

c = ((0,1),(2,3))

[i for i in c if i[0] == 0]
# result: [(0, 1)]

[i for i in c if i[0] == 3]
# result: []

列表组合为introduced in 2.0

答案 1 :(得分:2)

>>> c = ((0,1),(2,3))
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,),x))]
[(0, 1)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,1),x))]
[(0, 1)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,),x))]
[(2, 3)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,3),x))]
[(2, 3)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((4,),x))]
[]

使用更大的元组

>>> c=((0,1,2,3),(2,3,4,5))
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,1),x))]
[(0, 1, 2, 3)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((0,2),x))]
[]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,),x))]
[(2, 3, 4, 5)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((2,3,4),x))]
[(2, 3, 4, 5)]
>>> [x for x in c if all(1 if len(set(y)) is 1 else 0 for y in zip((4,),x))]
[]
>>>

修改:更紧凑的一个

>>> [x for x in c if all(len(set(y))==1 for y in zip((0,),x))]
[(0, 1, 2, 3)]

答案 2 :(得分:1)

我自己的解决方案,结合其他两个答案

f = lambda c, t: [x for x in c if t == x[:len(t)]]