简体   繁体   中英

Distill list of 3-tuples in Python

I have a list of 3-tuples (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. The z-component should be added up.

Any idea how to do this in a pythonic way?

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.

I'd use defaultdict : https://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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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