带有过滤器用法的python itertools groupby

问题描述 投票:0回答:1

我有一个列表= [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

[基本上,大于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)
python itertools
1个回答
0
投票

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

from itertools import groupby

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

result = []
for k, g in groupby(lst):
    lst = list(g)
    if k > 6 and len(lst) > 1:
        result.append(lst)
    else:
        result.extend(lst)

print(result)

输出:

[1, 2, 3, 3, 6, [8, 8], 10, 2, 5, [7, 7]]
© www.soinside.com 2019 - 2024. All rights reserved.