简体   繁体   English

用Python提取3元组的列表

[英]Distill list of 3-tuples in Python

I have a list of 3-tuples (x, y, z) ( http://pastebin.com/ZMgYKwvt ). 我有一个三元组(x,y,z)的列表( http://pastebin.com/ZMgYKwvt )。 I would like to distill "equal" entries into one. 我想将“相等”条目提炼成一个。 Equal means here that the pair (x, y) is the same in the triplet. 相等在这里表示三元组中的(x,y)对相同。 The z-component should be added up. z分量应加在一起。

Any idea how to do this in a pythonic way? 任何想法如何以pythonic的方式做到这一点?

eg: 例如:

(0, 1, 1)
(0, 1, 1)
(0, 1, 1)
(0, 3, 1)
(0, 3, 1)

should yield 应该屈服

(0, 1, 3)
(0, 3, 2)

Thx 谢谢

Try this: 尝试这个:

from collections import Counter as c
c(your_list)

This will give you something like: 这将为您提供以下信息:

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})

I'm sure you'll be able to pick it up from here! 我相信您可以在这里取货!

使用一set来查找唯一的项目,可以对它们进行排序(如果需要):

unique_tuples = sorted(set(list_of_tuples))
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]))]

This will do! 这样就可以了! It is almost like going over your algorithm verbally. 这几乎就像口头遍历您的算法一样。

You first group your elements according to your rule and sum the z coordinates to form new tuples. 您首先要根据规则对元素进行分组,然后将z坐标求和以形成新的元组。

I'd use defaultdict : https://docs.python.org/2/library/collections.html#collections.defaultdict 我会使用defaultdicthttps : //docs.python.org/2/library/collections.html#collections.defaultdict

from collections import defaultdict
d = defaultdict(lambda : 0) # initial value 0
for i in list_of_tuples:
    d[i[:2]] += i[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM