簡體   English   中英

將匹配的列表項分組直到更改然后重復

[英]Group matching list items until change then repeat

我正在嘗試將列表中的項目分組以顯示它們。 邏輯如下。

我有一個列表: 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]])

但是,這會不斷導致錯誤的輸出。

您可以使用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]]

您可以為此使用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]]

最嚴重的錯誤是使用唯一的temp_list 每次將temp_list添加到grouped_list它都是您添加的相同列表。 clear方法清空這個唯一列表。 相反, temp_list.clear()你應該做temp_list = []以獲得一個新列表。

您應該只迭代到len() - 1因為您可以訪問i + 1

還有其他問題,但這兩個是最重要的。

另外,不要使用list作為變量名,因為這會重新定義 Python 的標准項。 你可以這樣做,但這是一個壞主意。

沒有依賴:

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

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

結果:

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

不使用標准庫的“特殊”功能的答案。 (是向@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)

使用帶有一些內置結構(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

結果:

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

提示:避免使用“list”作為列表的名稱,因為它是 Python 結構的保留字。 這同樣適用於“dict”和“set”。

暫無
暫無

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

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