Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform search on a list of tuples

I have a list of tuples. For example, I have the following:

a=[('jamy', 'k'), ('Park', 'h'), ('kick', 'p'), ('an', 'o'),('an',
'o'),('an', 'o'),('an', 'r'), ('car', 'k'), ('rock', 'h'), ('pig',
'p')]

And another list,

b = ['k','h','p']

I would like to find the pattern in list b from second tuple element of list a.

Here in the above example the output should return,

[('jamy','Park','kick'),('car','rock','pig')]

Can someone help me to achieve my goals?

like image 347
Vysa Avatar asked Oct 26 '13 21:10

Vysa


People also ask

How do you iterate a list of tuples in Python?

Use the enumerate() function to iterate over a list of tuples, e.g. for index, tup in enumerate(my_list): . The enumerate function returns an object that contains tuples where the first item is the index, and the second is the value.


2 Answers

c = [(a[x][0], a[x+1][0], a[x+2][0])
                        for x, _ in enumerate(a) 
                                 if a[x][1] == b[0] and 
                                    a[x+1][1] == b[1] and
                                    a[x+2][1] == b[2]]
like image 190
cox Avatar answered Oct 15 '22 00:10

cox


Try this snippet.

list_of_values = [
    ('jamy', 'k'), ('Park', 'h'), ('kick', 'p'), ('an', 'o'), ('an', 'o'),
    ('an', 'o'), ('an', 'r'), ('car', 'k'), ('rock', 'h'), ('pig', 'p')
]
pattern = ('k','h','p')

# Important part
matches = [
    values for values, keys in (
        zip(*list_of_values[i:i + len(pattern)])
        for i in range(len(list_of_values) - len(pattern) + 1)
    ) if keys == pattern
]

print(matches)
>> [('jamy', 'Park', 'kick'), ('car', 'rock', 'pig')]
like image 31
OdraEncoded Avatar answered Oct 15 '22 01:10

OdraEncoded