Python 根据字符长度在子列表中拆分列表
我有一个字符串列表,我喜欢根据列表中单词的字符长度将该列表拆分为不同的“子列表”,例如:Python 根据字符长度在子列表中拆分列表,python,Python,我有一个字符串列表,我喜欢根据列表中单词的字符长度将该列表拆分为不同的“子列表”,例如: List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] 如何在python中实现这一点 谢谢我认为你应该使用字典 >>> dict_sublist = {} >>> for el in List: ... dict_subl
List = [a, bb, aa, ccc, dddd]
Sublist1 = [a]
Sublist2= [bb, aa]
Sublist3= [ccc]
Sublist2= [dddd]
如何在python中实现这一点
谢谢我认为你应该使用字典
>>> dict_sublist = {}
>>> for el in List:
... dict_sublist.setdefault(len(el), []).append(el)
...
>>> dict_sublist
{1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['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]
by_length=[]
对于列表中的单词:
wl=len(字)
而len(按长度)
使用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)]
>>> 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']]