如何在python列表中合并每5个列表?

时间:2018-07-29 20:44:00

标签: python list append iteration

嗨,我的清单很大。

说,它看起来像下面。

list = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]

我想将每5个列表合并为一个元素列表,依此类推。 我列表中总共有150995个列表。

预期输出:

new_list = [['a' , 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

我尝试了以下代码。但只限于一个列表。

list(zip(*list)[0])

预先感谢

7 个答案:

答案 0 :(得分:3)

您基本上希望将大小均匀的列表分组。可以使用itertools.chain并使用range进行切片,并执行5步

import itertools

lst = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]

result = [list(itertools.chain.from_iterable(itertools.islice(lst,i,i+5))) for i in range(0,len(lst),5)]


print(result)

结果:

[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

注释:

  • 使用itertools.islice避免了标准的lst[i:i+5]切片,该切片会创建无用的list对象
  • 即使元素的数量不能被5整除,它也可以工作。

答案 1 :(得分:1)

给出:

>>> li = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]

您可以这样做:

>>> list(map(list, zip(*[iter([e for sublist in li for e in sublist])]*5)))
[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

或者,

>>> [[e for sublist in lst[i:i+5] for e in sublist] for i in range(0,len(lst),5)]
[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

答案 2 :(得分:0)

使用itertools.chain展平列表,并使用itertools.zip_longest将元素分为5个组

>>> from itertools import zip_longest, chain
>>> n = 5
>>> list(zip_longest(*[chain(*List)]*n))    
[('a', 'b', 'c', '1234', 'd'), ('e', 'g', 'h', 'i', '56')]

如果对结果为元组列表不满意,则可以使用map

将元组中的各个元素转换为列表
>>> list(map(list, zip_longest(*[chain(*List)]*5)))
[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

答案 3 :(得分:0)

此解决方案很方便,因为它除了numpy之外均不使用

如果您的列表中总是有被5整除的元素,那么

import numpy as np
oldlist = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]
newlist = np.reshape(oldlist,(len(oldlist)//5,5)).T.tolist()

新列表将具有所需的

输出
[['a' , 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

答案 4 :(得分:0)

许多好的解决方案。我只是想添加另一个使用自定义Iterator的可能性,如下所示:

from itertools import chain


class MyIter:
    def __init__(self, lists,n_first):
        self.lists = lists
        self.index = 0
        self.n_first = n_first

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.lists):

            temp = list(chain(*self.lists[self.index:min(self.index+self.n_first,len(self.lists))]))
            self.index += self.n_first
            return temp
        else:
            raise StopIteration

_list = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]

print(list(MyIter(_list,5)))

答案 5 :(得分:0)

假设len(list)是5的倍数,则以下解决方案有效:

list = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]
row = int(len(list)/5)
new_list = [i.tolist() for i in np.array(list).reshape((row,5))]
print (new_list)

导致

[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]

答案 6 :(得分:0)

这是一个非图书馆列表理解解决方案:

res = [[j[0] for j in l[i:i+5]] for i in range(0, len(l), 5)]

print(res)

使用repl

顺便说一句,调用列表list重新定义了一个内置函数。