Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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


like image 639
Okeh Avatar asked Nov 21 '25 14:11

Okeh


2 Answers

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']]
like image 183
Sash Sinha Avatar answered Nov 24 '25 04:11

Sash Sinha


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']]
like image 27
blhsing Avatar answered Nov 24 '25 05:11

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!