如何在Python中将长度相同的字符串列表组合并创建嵌套列表

3

我有一个字符串列表。根据每个字符串的长度,我需要将它们分组到一个列表中。最终,一个列表应该包含所有的列表。

示例:

输入

in=['the', 'way', 'you', 'see', 'people', 'is', 'the', 'way', 'you', 'treat', 'them', 'and', 'the', 'way', 'you', 'treat', 'them', 'is', 'what', 'they', 'become']

输出

expected_out=[['is'],['and', 'see', 'the', 'way', 'you'], ['them', 'they', 'what'], ['treat'], ['become', 'people']]

你尝试过哪些代码? - pzp
脑海中想到的方法:创建一个循环,它会递增一个计数器(将其初始化为最小单词长度)。对于每次循环,检查单词的长度。如果len(word) == counter_value,则将该单词添加到临时列表中并将其删除,以便下次不再检查。循环结束后,将临时列表添加到“主”列表(2D列表)中,清空临时列表,递增计数器并重新开始。这可能是一种愚蠢的方法 - 我不知道。但在我的脑海中它是可行的 :P - jDo
3个回答

4

我不确定这是否是最好的方法,但这是我想到的第一件事:

from collections import defaultdict

len2words = defaultdict(set)

for word in input_list:
    len2words[len(word)].add(word)

output = [list(len2words[key]) for key in sorted(len2words.keys())]

4
您可以使用itertools.groupby实现如下功能:
from itertools import groupby

l = ['the', 'way', 'you', 'see', 'people', 'is', 'the', 'way',
      'you', 'treat', 'them', 'and', 'the', 'way', 'you', 'treat',
      'them', 'is', 'what', 'they', 'become']

l.sort(key=len)
output = [list(set(items)) for length, items in groupby(l, key=len)]
print(output)

输出

[['is'], ['and', 'the', 'see', 'you', 'way'], ['them', 'what', 'they'], 
 ['treat'], ['become', 'people']]

在将具有相同长度的连续字符串分组之前,先按长度对字符串进行排序。然后使用列表推导式通过使用set来将唯一的字符串解包成子列表。


非常感谢!这帮助我解决了难题。 - user6054437

1
我会使用itertools.groupby结合sorted,以不修改原始输入数据的顺序。
data = ['the', 'way', 'you', 'see', 'people', 'is', 'the', 'way',
     'you', 'treat', 'them', 'and', 'the', 'way', 'you', 'treat', 
     'them', 'is', 'what', 'they', 'become']

sorted_data = sorted(data, key=len)
result = [list(set(group[1])) for group in groupby(sorted_data, key=len)]

'''
[['is'], 
 ['and', 'the', 'see', 'you', 'way'], 
 ['them', 'what', 'they'], 
 ['treat'], 
 ['become', 'people']]
'''

我会把它分开一点。现在这样很难阅读。 - zondo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接