I've got a list of strings and I'm trying to make a list of lists of strings by string length.
i.e.
['a', 'b', 'ab', 'abc']
becomes
[['a', 'b'], ['ab'], ['abc']]
I've accomplished this like so:
lst = ['a', 'b', 'ab', 'abc']
lsts = []
for num in set(len(i) for i in lst):
lsts.append([w for w in lst if len(w) == num])
I'm fine with that code, but I'm trying to wrap my head around comprehensions. I want to use nested comprehensions to do the same thing, but I can't figure out how.
This can be done using the following steps: Get the length of a list using len() function. If the length of the parts is not given, then divide the length of list by 2 using floor operator to get the middle index of the list.
>>> [[w for w in L if len(w) == num] for num in set(len(i) for i in L)]
[['a', 'b'], ['ab'], ['abc']]
Also, itertools
is likely to be a little more efficient.
lst = ['a', 'b', 'ab', 'abc']
lst.sort(key=len) # does not make any change on this data,but
# all strings of given length must occur together
from itertools import groupby
lst = [list(grp) for i,grp in groupby(lst, key=len)]
results in
[['a', 'b'], ['ab'], ['abc']]
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