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']]
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']]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With