Rom*_*meo 3 python group-by list python-itertools
我有一个列表 = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7] 我正在尝试使用 groupby 将其转换为
1
2
3
3
6
8,8
10
2,
5
7,7
Run Code Online (Sandbox Code Playgroud)
基本上,任何大于 6 的东西,我喜欢将它们分组,否则我想让它们不分组。有关如何使用 itertool groupby 执行此操作的任何提示
我目前的代码:
for key, group in it.groupby(numbers, lambda x: x):
f = list(group)
if len(f) == 1:
split_list.append(group[0])
else:
if (f[0] > 6): #filter condition x>6
for num in f:
split_list.append(num + 100)
else:
for num in f:
split_list.append(num)
Run Code Online (Sandbox Code Playgroud)
您可以使用对长度大于 1 的itertools.groupby所有元素进行分组。所有其他元素保持未分组状态。6
如果我们希望组作为独立列表,我们可以使用append. 如果我们想要扁平化组,我们可以使用extend.
from itertools import groupby
lst = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7]
result = []
for k, g in groupby(lst):
group = list(g)
if k > 6 and len(group) > 1:
result.append(group)
else:
result.extend(group)
print(result)
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3, 3, 6, [8, 8], 10, 2, 5, [7, 7]]
Run Code Online (Sandbox Code Playgroud)