Python, a concise way to verify collection membership using partial matching

What is the pythonic way to check if there is a tuple starting from another tuple in the collection? in fact, I'm really after the compliance index, but I can probably figure out from the test case

eg:

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

I have to add my python 2.4 and / or 2.5

thanks

+4
source share
3 answers

Edit: Thanks to OP for an additional explanation of the problem.
The attachments of nested lists to S.Mark are rather malicious; check them out.

I can choose a helper 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 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: [] 

The comps list was introduced in version 2.0 .

+3
source
 >>> 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 big 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 : will be more compact

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

my own decision, a combination of two other answers

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

Source: https://habr.com/ru/post/1307754/


All Articles