python itertools groupby with filter usage



>我有一个列表 = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7] 我正在尝试使用分组将其转换为

1
2
3
3
6
8,8
10
2,
5
7,7

基本上,任何大于 6 的东西,我喜欢将它们分组,否则我想将它们取消分组。 关于如何使用迭代工具分组执行此操作的任何提示

我的代码目前:

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)

可以使用itertools.groupby对所有大于6的元素和长度大于 1 的组进行分组。所有其他元素保持未分组状态。

如果我们希望组作为独立列表,我们可以使用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)

输出:

[1, 2, 3, 3, 6, [8, 8], 10, 2, 5, [7, 7]]

您可以使用如下所示flatten()函数。 此函数是从 https://stackoverflow.com/a/40857703/501852 修改的版本

下面的函数是一个生成器对象(python ver>= 3.8(。

新增调节功能作为输入参数。

from typing import Iterable 
def flatten(items, cond_func=lambda x: True):
"""Yield items from any nested iterable"""
for x in items:
if isinstance(x, Iterable) 
and not isinstance(x, (str, bytes)) 
and cond_func(x):    # Conditioning function
yield from flatten(x)
else:
yield x

然后,您可以使用list comprehension变体:

res = flatten( [list(g) for k, g in groupby(lst)],
cond_func = lambda x: x[0] <= 6 or len(x) == 1)
# Conditions to flatten
print(res)

您可以使用generator变体:

res = flatten( (list(g) for k, g in groupby(lst)),
cond_func = lambda x: x[0] <= 6 or len(x) == 1)
# Conditions to flatten
print(list(res))

输出为

[1, 2, 3, 3, 6, [8, 8], 10, 2, 5, [7, 7]]

最新更新