使用过滤器的python itertools groupby

2024-06-28 15:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

基本上,如果大于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)

Tags: key代码in列表forifgroupit
2条回答

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

下面的函数是一个生成器对象(pythonver>;=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]]

可以使用^{}对大于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]]

相关问题 更多 >