0

我有这样的数据结构:

[
    { "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+1some_event()然后第三行(蓝色)和第四行(黄色)没有任何反应,第五和第六行(蓝色)用 values5+8等触发。

谢谢!

4

1 回答 1

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))
于 2012-11-08T17:14:47.033 回答