'Python group consecutive elements of a list into two's without repetition
I got the the list below
[[0,1],[0,1,2,3,4,5,6,7],[0,1,2,3]]
Using Python, how can I iterate through the list to get
[[0,1],[0,1],[2,3],[4,5],[6,7],[0,1],[2,3]]
?
Solution 1:[1]
What we do is we first flatten the list and then we index the flattened list to the 2d list
l1 = [[0,1],[0,1,2,3,4,5,6,7],[0,1,2,3]]
def fix(l1):
l1 = [item for sublist in l1 for item in sublist]
l1 = [l1[i:i+2] for i in range(0, len(l1), 2)]
return l1
l1 = fix(l1)
print(l1)
Output:
[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]
Solution 2:[2]
You can use zip(item[::2], item[1::2]) to grab pairs of elements, turn these tuples into lists using map() and list(), and then generate the final result using itertools.chain.from_iterable() and list():
from itertools import chain
list(map(list, chain.from_iterable(zip(item[::2], item[1::2]) for item in data)))
This outputs:
[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]
Solution 3:[3]
The key to one solution for this is taking advantage of the standard library itertools chain function, specifically, chain.from_iterable It flattens out the elements in an iterable of iterables allowing you to reconstitute them into pairs, for example.
from itertools import chain
twos_list = []
pair_list = []
for x in chain.from_iterable([[0,1],[0,1,2,3,4,5,6,7],[0,1,2,3]]):
pair_list.append(x)
if len(pair_list) == 2:
twos_list.append(pair_list)
pair_list = []
print(twos_list)
[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | BrokenBenchmark |
| Solution 3 | rhurwitz |
