简体   繁体   English

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

[英]Group matching list items until change then repeat

I am trying to group items in a list to display them.我正在尝试将列表中的项目分组以显示它们。 The logic is the following.逻辑如下。

I have a list: list = [1,1,2,3,4,4,5,5,6] I want to turn this into: grouped_list = [[1,1],[2],[3],[4,4],[5,5],[6]]我有一个列表: list = [1,1,2,3,4,4,5,5,6]我想把它变成: grouped_list = [[1,1],[2],[3],[4,4],[5,5],[6]]

I have tried the following:我尝试了以下方法:

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]])

However, this keeps resulting in the wrong output.但是,这会不断导致错误的输出。

You can use itertools.groupby您可以使用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]]

You could use a collections.defaultdict for that:您可以为此使用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]]

The worst error is the use of an unique temp_list .最严重的错误是使用唯一的temp_list Each time you add temp_list to grouped_list it is the same list that you add.每次将temp_list添加到grouped_list它都是您添加的相同列表。 The clear method empty this unique list. clear方法清空这个唯一列表。 Instead temp_list.clear() you should do temp_list = [] to have a new list.相反, temp_list.clear()你应该做temp_list = []以获得一个新列表。

You should iterate only to len() - 1 because you do an access to i + 1 .您应该只迭代到len() - 1因为您可以访问i + 1

There are other problems, but these two are the most important.还有其他问题,但这两个是最重要的。

Also, don't use list for a variable name, because that redefine a standard item of Python.另外,不要使用list作为变量名,因为这会重新定义 Python 的标准项。 You could that, but it is a bad idea.你可以这样做,但这是一个坏主意。

Without dependencies:没有依赖:

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

c = list()
for n in set(l):
    c.append( [n]*l.count(n) )

Result:结果:

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

An answer without use of a "special" function of the standard library.不使用标准库的“特殊”功能的答案。 (It is to show to @Adam. I think that the answer of @abc with itertools.groupby() is the better answer.) (是向@Adam 展示。我认为@abc 与itertools.groupby()的答案是更好的答案。)

seq = [1, 1, 2, 3, 4, 4, 5, 5, 6]
print(seq)


temp_seq = []
grouped_seq = []
previous = None

for n in seq:
    if previous != n:
        previous = n
        if temp_seq:
            grouped_seq.append(temp_seq)
            temp_seq = []

    temp_seq.append(n)

if temp_seq:
    grouped_seq.append(temp_seq)


print(grouped_seq)

Use a list comprehension with some built-in structures (repeat, count and set) :使用带有一些内置结构(repeat、count 和 set)的列表推导式:

import numpy as np

lis = [1,1,2,3,4,4,5,5,6] 
grouped_list = [np.repeat(x, lis.count(x)).tolist() for x in set(lis)]
grouped_list

Result:结果:

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

Hint: avoid use "list" as a name for your lists, since it is a reserved word for a Python structure.提示:避免使用“list”作为列表的名称,因为它是 Python 结构的保留字。 The same is valid for "dict" and "set".这同样适用于“dict”和“set”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM