根据字符长度拆分子列表中的列表

时间:2013-08-19 12:50:22

标签: python

我有一个字符串列表,我喜欢根据列表中单词的字符长度将该列表拆分为不同的“子列表”,例如:

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

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

我如何在python中实现这一目标?

谢谢

4 个答案:

答案 0 :(得分:7)

使用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)]

结果是:

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

如果您的列表已经按字符串长度排序,而您只需要进行分组,那么您可以将代码简化为:

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

答案 1 :(得分:2)

我认为你应该使用字典

>>> dict_sublist = {}
>>> for el in List:
...     dict_sublist.setdefault(len(el), []).append(el)
... 
>>> dict_sublist
{1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']}

答案 2 :(得分:1)

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

答案 3 :(得分:0)

假设您对列表列表感到满意,按长度编制索引,

之类的内容如何
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]