abinitio
abinitio

Reputation: 805

List of lists python: combine list elements that are the same size

I have a list of lists in python:

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

I would like to combine the sublists into a single sublist if they hold the same number of elements:

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

Is there a simple way of doing this?

Upvotes: 1

Views: 377

Answers (3)

sheldonzy
sheldonzy

Reputation: 5941

A "simpler" approach without itertools:

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

output:

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

Upvotes: 1

CIsForCookies
CIsForCookies

Reputation: 12817

Here is my approach (without using 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]]

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Use groupby and chain from itertools

Ex:

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)

Output:

[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
  • sorted(lst, key=lambda h: len(h)) to sort your list by len
  • then use groupby to group your list by len of list

Upvotes: 5

Related Questions