迭代列表的序列+添加相同键的值

时间:2012-11-08 16:59:25

标签: python sorting iteration

我有这样的数据结构:

[
    { "key" : { "subkey" : "red", "value" : 1 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "blue", "value" : 1 }  },
    { "key" : { "subkey" : "yellow", "value" : 3 }  },
    { "key" : { "subkey" : "blue", "value" : 5 }  },
    { "key" : { "subkey" : "blue", "value" : 8 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "red", "value" : 3 }  },
    { "key" : { "subkey" : "red", "value" : 6 }  },
]

这个想法是我想迭代它,当至少2 "subkeys"相同时,触发some_event(),这会将这些连续对象的值相加,直到它达到再次提出不同的"subkey"

例如,第一个和第二个dicts应触发some_event()并添加值2+1。然后第三条(蓝色)和第四条(黄色)线条没有任何反应,第五条和第六条(蓝色)点燃some_event(),值为5+8等。

谢谢!

1 个答案:

答案 0 :(得分:1)

from itertools import groupby

L = [
    { "key" : { "subkey" : "red", "value" : 1 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "blue", "value" : 1 }  },
    { "key" : { "subkey" : "yellow", "value" : 3 }  },
    { "key" : { "subkey" : "blue", "value" : 5 }  },
    { "key" : { "subkey" : "blue", "value" : 8 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "red", "value" : 3 }  },
    { "key" : { "subkey" : "red", "value" : 6 }  },
]


def some_event(*args):
    print args, sum(args)


for k, g in groupby(L, key=lambda x:x["key"]["subkey"]):
    g = list(g)
    if len(g) > 1:
        some_event(*(i["key"]["value"] for i in g))