簡體   English   中英

用Python提取3元組的列表

[英]Distill list of 3-tuples in Python

我有一個三元組(x,y,z)的列表( http://pastebin.com/ZMgYKwvt )。 我想將“相等”條目提煉成一個。 相等在這里表示三元組中的(x,y)對相同。 z分量應加在一起。

任何想法如何以pythonic的方式做到這一點?

例如:

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

應該屈服

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

謝謝

嘗試這個:

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

我相信您可以在這里取貨!

使用一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]))]

這樣就可以了! 這幾乎就像口頭遍歷您的算法一樣。

您首先要根據規則對元素進行分組,然后將z坐標求和以形成新的元組。

我會使用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