分组匹配列表项,直到更改然后重复

问题描述 投票:0回答:3

我正在尝试将列表中的项目分组以显示它们。逻辑如下。

我有一个清单:list = [1,1,2,3,4,4,5,5,6]我想把它变成:grouped_list = [[1,1],[2],[3],[4,4],[5,5],[6]]

我尝试了以下操作:

for i in range(0, len(list)):
    if(list[i] == list[i+1]):
        temp_list.append(list[i])
    else:
        grouped_list.append(temp_list)
        temp_list.clear()
        grouped_list.append([list[i]])

但是,这总是导致错误的输出。

python python-3.x list
3个回答
0
投票

您可以为此使用collections.defaultdict

from collections import defaultdict

your_list = [1, 1, 2, 3, 4, 4, 5, 5, 6]

your_dict = defaultdict(list)
for i in your_list:
    your_dict[i].append(i)

result = sorted(your_dict.values())  # Skip this line if order doesn't matter
print(result)
# [[1, 1], [2], [3], [4, 4], [5, 5], [6]]

0
投票

您可以使用itertools.groupby

>>> l = [1,1,2,3,4,4,5,5,6]
>>> res = [list(grp) for k, grp in itertools.groupby(l)]
>>> res
[[1, 1], [2], [3], [4, 4], [5, 5], [6]]

0
投票

最严重的错误是使用唯一的temp_list。每次将temp_list添加到grouped_list时,它就是添加的same列表。 clear方法清空此唯一列表。相反,您应该执行temp_list.clear()来创建新列表。

您应该仅访问temp_list = [],因为您可以访问len() - 1

还有其他问题,但这两个是最重要的。

此外,请勿将i + 1用作变量名,因为这会重新定义Python的标准项。您可以这样做,但这是个坏主意。

© www.soinside.com 2019 - 2024. All rights reserved.