我有字符串的列表,我喜歡根據在第列表例如單詞的字符長度來分割該列表在不同的「子列表」:拆分根據字符內長度在子列表的列表
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中實現這一點?
謝謝
我認爲你應該使用字典
>>> 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]
通過使用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']]