清单清单python:合并大小相同的清单元素

时间:2018-08-23 10:35:50

标签: python python-3.x list list-comprehension

我在python中有一个列表列表:

[[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]

如果子列表包含相同数量的元素,我想将它们组合成一个子列表:

[[1,2,17],[3,4,5,6],[7,8,9,10,11,12,13,14,15,16]]

是否有一种简单的方法?

3 个答案:

答案 0 :(得分:5)

使用groupby中的chainitertools

例如:

from itertools import groupby, chain

lst = [[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]

result = [list(chain.from_iterable(v)) for k, v in groupby(sorted(lst, key=lambda h: len(h)), lambda x: len(x))]
print(result)

输出:

[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
  • sorted(lst, key=lambda h: len(h))按len排序您的列表
  • 然后使用groupby按列表的len对列表进行分组

答案 1 :(得分:1)

一种没有itertools的“简单”方法:

dictByLength = {}
for i in mylist:
    dictByLength[len(i)] = dictByLength.get(len(i), []) + i
print(list(dictByLength.values()))

输出:

[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]

答案 2 :(得分:0)

这是我的方法(不使用itertools):

l = [[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]

# create one sublist for each possible length
m = [[] for size in range(len(max(l, key=len)))]

# append to each size-sublist, the appropriate sublist
for sub_l in l:
    size = len(sub_l)
    m[size - 1] += sub_l

# remove empty sub lists
m = [sub_m for sub_m in m if sub_m]

print(m)

[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]