Home > front end >  Python group consecutive elements of a list into two's without repetition
Python group consecutive elements of a list into two's without repetition

Time:04-24

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]]

CodePudding user response:

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]]

CodePudding user response:

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]]

CodePudding user response:

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]]
  • Related