我有一个字符串列表,我喜欢根据列表中单词的字符长度将该列表拆分为不同的“子列表”,例如:
List = [a, bb, aa, ccc, dddd]
Sublist1 = [a]
Sublist2= [bb, aa]
Sublist3= [ccc]
Sublist2= [dddd]
我怎样才能在 python 中实现这一点?
谢谢
我有一个字符串列表,我喜欢根据列表中单词的字符长度将该列表拆分为不同的“子列表”,例如:
List = [a, bb, aa, ccc, dddd]
Sublist1 = [a]
Sublist2= [bb, aa]
Sublist3= [ccc]
Sublist2= [dddd]
我怎样才能在 python 中实现这一点?
谢谢
通过使用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)]
我认为你应该使用字典
>>> 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']]
假设您对按长度索引的列表列表感到满意,那么类似
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]