views:

72

answers:

3

hello.

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

+2  A: 

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.

Adam Bernier
yes, it works for me. However I really like to know how to compare tuples, rather than individual members, e.g. `(0,1,2) == (0,1,2,3)[:len(((0,1,2)))]` (which does not seem pythonic)
aaa
+2  A: 
>>> 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)]
S.Mark
okay, slight modification `[x for x in c if all(len(set(y)) is 1 for y in zip((0,),x))] `
aaa
Oh, I just posted similar one too @aaa with ==1, may be 2 space less
S.Mark
+1  A: 

my own solution, combination of two other answers

f = lambda c, t: [x for x in c if t == x[:len(t)]]
aaa
+1 for answering your own question :-) And thanks for expanding on your problem. I posted something similar in my answer.
Adam Bernier

related questions