IterTools使用lambda函数分组,如果列表的子列表在索引0和1处有匹配值,则将它们分组在一起

发布时间:2022-06-14 / 作者:清心寡欲
本文介绍了IterTools使用lambda函数分组,如果列表的子列表在索引0和1处有匹配值,则将它们分组在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表列表:

data = [['a', 'b', 2000, 100], ['a', 'b', 4000, 500], ['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000], ['a', 'd', 2000, 100], ['a', 'd', 1000, 100]]

如果它们具有相同的前两个值,我想将它们组合在一起。输出将为:

data = [(['a', 'b', 2000, 100], ['a', 'b', 4000, 500]), (['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000]), (['a', 'd', 2000, 100], ['a', 'd', 1000, 100])]

前两个值相同的子列表在List中总是相邻的,但它们需要分组的数量不同。

我尝试过:

from itertools import groupby
data = [['a', 'b', 2000, 100], ['a', 'b', 4000, 500], ['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000], ['a', 'd', 2000, 100], ['a', 'd', 1000, 100]]
output = [list(group) for key, group in groupby(data, lambda x:x[0])]

new_data = []
for l in output:
    new_output = [tuple(group) for key, group in groupby(l, lambda x:x[1])]
    for grouped_sub in new_output:
        new_data.append(grouped_sub)

print(new_data)

并获得输出:

[(['a', 'b', 2000, 100], ['a', 'b', 4000, 500]), (['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000]), (['a', 'd', 2000, 100], ['a', 'd', 1000, 100])]

这正是我要找的。但是,我的列表列表是len(data) = 1000000,我知道如果我可以完全跳过for循环,并以某种方式使groupbylambda在分组时同时考虑x[0]x[1],这可能会更有效率。但我还不太明白lambda中的lambda功能是如何运行得很好的。

推荐答案

为什么不直接按前两项分组:

from itertools import groupby

data = [['a', 'b', 2000, 100], ['a', 'b', 4000, 500], ['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000], ['a', 'd', 2000, 100], ['a', 'd', 1000, 100]]
res = [tuple(g) for k, g in groupby(data, key=lambda x: x[:2])]
print(res)

输出:

[(['a', 'b', 2000, 100], ['a', 'b', 4000, 500]), (['c', 'd', 500, 8000], ['c', 'd', 60, 8000], ['c', 'd', 70, 1000]), (['a', 'd', 2000, 100], ['a', 'd', 1000, 100])]

这篇关于IterTools使用lambda函数分组,如果列表的子列表在索引0和1处有匹配值,则将它们分组在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Itertools groupby with lambda function, group sublists of a list together if they have matching values at indices 0 and 1


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。