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?
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.
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]]
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With