簡體   English   中英

根據字符長度在子列表中拆分列表

[英]Split a list in sublists according to charcter length

我有一個字符串列表,我想根據列表中單詞的字符長度將該列表分為不同的“子列表”,例如:

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]    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM