Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: split list of strings to a list of lists of strings by length with a nested comprehensions

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.

like image 432
dustin Avatar asked Jul 04 '12 19:07

dustin


People also ask

How do I split a list into a sub list?

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.


2 Answers

>>> [[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.

like image 197
Ignacio Vazquez-Abrams Avatar answered Oct 25 '22 04:10

Ignacio Vazquez-Abrams


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']]
like image 1
Hugh Bothwell Avatar answered Oct 25 '22 05:10

Hugh Bothwell