Python 将列表的连续元素分成两个,不重复

Python group consecutive elements of a list into two's without repetition

我得到了下面的列表

[[0,1],[0,1,2,3,4,5,6,7],[0,1,2,3]]

使用Python,如何遍历列表得到

[[0,1],[0,1],[2,3],[4,5],[6,7],[0,1],[2,3]]

?

我们所做的是首先展平列表,然后将展平的列表索引到二维列表

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)

输出:

[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]

一个解决方案的关键是利用标准库 itertools chain 函数,具体来说,chain.from_iterable 它可以将可迭代对象中的元素展平,让您可以将它们重新组合成对,例如.

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

你可以使用zip(item[::2], item[1::2])获取成对的元素,使用map()list()将这些元组变成列表,然后使用itertools.chain.from_iterable()和生成最终结果list():

from itertools import chain

list(map(list, chain.from_iterable(zip(item[::2], item[1::2]) for item in data)))

这输出:

[[0, 1], [0, 1], [2, 3], [4, 5], [6, 7], [0, 1], [2, 3]]