[英]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.