我有一个3元组(x,y,z)(http://pastebin.com/ZMgYKwvt)的列表。我想将“平等”条目提炼成一个。这里相等意味着对(x,y)在三元组中是相同的。应该加上z分量。
知道如何以pythonic的方式做到这一点吗?
e.g:
(0, 1, 1)
(0, 1, 1)
(0, 1, 1)
(0, 3, 1)
(0, 3, 1)
应该产生
(0, 1, 3)
(0, 3, 2)
THX
答案 0 :(得分:1)
试试这个:
from collections import Counter as c
c(your_list)
这会给你类似的东西:
Counter({(4, 4, 1): 20, (0, 1, 1): 9, (0, 0, 1): 8, (5, 5, 1): 7, (5, 4, 1): 7, (1, 1, 1): 7, (1, 4, 1): 4, (0, 4, 1): 3, (3, 3, 1): 3, (0, 3, 1): 2, (1, 5, 1): 2, (0, 2, 1): 2, (3, 2, 1): 1, (2, 2, 1): 1, (2, 3, 1): 1, (0, 5, 1): 1})
我相信你能从这里拿起它!
答案 1 :(得分:1)
使用set
查找可以排序的唯一项目(如果需要):
unique_tuples = sorted(set(list_of_tuples))
答案 2 :(得分:1)
from itertools import groupby
sorted_list = sorted(your_list)
# sorting makes tuples with same 'key' next to each other
sum_z = lambda tuples: sum(t[2] for t in tuples)
your_ans = [(k[0], k[1], sum_z(g))
for k, g in groupby(sorted_list, lambda t: (t[0], t[1]))]
这样做!这几乎就像是以口头方式审阅你的算法。
首先根据规则对元素进行分组,然后将z坐标相加以形成新元组。
答案 3 :(得分:1)
我使用<apex:outputpanel rendered="{!recordtype=='whatever id'}">
<apex:pageblock table>
<!-- show all your columns -->
:https://docs.python.org/2/library/collections.html#collections.defaultdict
defaultdict