How to create a list of tuples with adjacent list elements if a condition is true ?
How to create a list of tuples with adjacent list elements if a condition is true ?
The best way of approach:
[(x,y) for x,y in zip(myList, myList[1:]) if y == 9] [(8, 9), (4, 9), (7, 9)]
The above code is explained here:
- zip(some_list, some_list[1:]) would generate a list of pairs of adjacent elements.
- Now with that tuple, filter on the condition that the second element is equal to 9.
we can also do it without slicing by creating iterators:
l = myList = [1,8,9,2,4,9,6,7,9,8] it1, it2 = iter(l), iter(l) # consume first element from it2 -> leaving 8,9,2,4,9,6,7,9,8 next(it2, "") # then pair up, (1,8), (8,9) ... print([(i, j) for i,j in zip(it1, it2) if j == 9])
Or use the pairwise recipe to create your pairs
from itertools import tee, izip def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b)
Just import tee and use the regular zip for python3,
The code can be used to make Tuples with adjacent list elements
myList = [9, 1, 8, 9, 2, 4, 9, 6, 7, 9, 8] [(myList[i-1], x) for i, x in enumerate(myList) if x==9 and i!=0] # [(8, 9), (4, 9), (7, 9)]