Python, concise way to test membership in collection using partial match
What is the pythonic way to test if there is a tuple starting with another tuple in collection? actually, I am really after the index of match, but I can probably figure out from test example
for example:
c = ((0,1),(2,3))
# (0,) should match first element, (3,)should match no element
I should add 开发者_如何学编程my python is 2.4 and/or 2.5
thanks
Edit:
Thanks to the OP for the addition explanation of the problem.
S.Mark's nested list comprehensions are pretty wicked; check 'em out.
I might opt to use an auxiliary function:
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
Original answer:
Does using a list-comprehension work for you?:
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: []
List comps were introduced in 2.0.
>>> 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))]
[]
With larger Tuple
>>> 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))]
[]
>>>
Edit: more compact one would be
>>> [x for x in c if all(len(set(y))==1 for y in zip((0,),x))]
[(0, 1, 2, 3)]
my own solution, combination of two other answers
f = lambda c, t: [x for x in c if t == x[:len(t)]]
精彩评论