Okeh
Okeh

Reputation: 163

Splitting a list of strings into sub lists based on their length

If for instance I have a list

['My', 'Is', 'Name', 'Hello', 'William']

How can I manipulate it such that I can create a new list

[['My', 'Is'], ['Name'], ['Hello'], ['William']]


Upvotes: 2

Views: 662

Answers (4)

Sash Sinha
Sash Sinha

Reputation: 22420

You could use itertools.groupby:

>>> from itertools import groupby
>>> l = ['My', 'Is', 'Name', 'Hello', 'William']
>>> [list(g) for k, g in groupby(l, key=len)]
[['My', 'Is'], ['Name'], ['Hello'], ['William']]

If however the list is not already sorted by length you will need to sort it first as @recnac mentions in the comments below:

>>> l2 = ['My', 'Name', 'Hello', 'Is', 'William']
>>> [list(g) for k, g in groupby(sorted(l2, key=len), key=len)]
[['My', 'Is'], ['Name'], ['Hello'], ['William']]

Upvotes: 7

Okeh
Okeh

Reputation: 163

Hi guys I have also found a solution, while it is not the most concise I thought it would be worth sharing

data = ['My', 'Is', 'Name', 'Hello', 'William']
dict0 = {}
for index in data:
    if len(index) not in dict0:
        dict0[len(index)] = [index]
    elif len(index) in dict0:
        dict0[len(index)] += [index]
list0 = []
for i in dict0:
    list0.append(dict0[i])
print(list0)

Upvotes: 2

blhsing
blhsing

Reputation: 106881

You can build a dict that maps word lengths to a list of matching words, and then get the list of the dict's values:

l = ['My', 'Is', 'Name', 'Hello', 'William']
d = {}
for w in l:
    d.setdefault(len(w), []).append(w)
print(list(d.values()))

This outputs:

[['My', 'Is'], ['Name'], ['Hello'], ['William']]

Upvotes: 2

recnac
recnac

Reputation: 3744

you can use dict to record the string group by length, defaultdict is used for convenient here.

from collections import defaultdict

str_list = ['My', 'Is', 'Name', 'Hello', 'William']
group_by_len = defaultdict(list)
for s in str_list:
    group_by_len[len(s)].append(s)

result = list(group_by_len.values())

output: [['My', 'Is'], ['Name'], ['Hello'], ['William']]

Hope that will help you, and comment if you have further questions. : )

Upvotes: 1

Related Questions