简体   繁体   中英

Split a list in sublists according to charcter length

I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list eg:

List = [a, bb, aa, ccc, dddd]

Sublist1 = [a]
Sublist2= [bb, aa]
Sublist3= [ccc]
Sublist2= [dddd]

How can i achieve this in python ?

Thank you

by using itertools.groupby :

 values = ['a', 'bb', 'aa', 'ccc', 'dddd', 'eee']
 from itertools import groupby
 output = [list(group) for key,group in groupby(sorted(values, key=len), key=len)]

The result is:

[['a'], ['bb', 'aa'], ['ccc', 'eee'], ['dddd']]

If your list is already sorted by string length and you just need to do grouping, then you can simplify the code to:

 output = [list(group) for key,group in groupby(values, key=len)]

I think you should use dictionaries

>>> dict_sublist = {}
>>> for el in List:
...     dict_sublist.setdefault(len(el), []).append(el)
... 
>>> dict_sublist
{1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']}
>>> from collections import defaultdict
>>> l = ["a", "bb", "aa", "ccc", "dddd"]
>>> d = defaultdict(list)
>>> for elem in l:
...     d[len(elem)].append(elem)
...
>>> sublists = list(d.values())
>>> print(sublists)
[['a'], ['bb', 'aa'], ['ccc'], ['dddd']]

Assuming you're happy with a list of lists, indexed by length, how about something like

by_length = []
for word in List:
   wl = len(word)
   while len(by_length) < wl:
      by_length.append([])
   by_length[wl].append(word)

print "The words of length 3 are %s" % by_length[3]    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM