如果前两个元素是相同的,则在元组列表中添加第三个元素,每个元素包含三个元素

时间:2017-01-20 11:04:14

标签: python list tuples

如果前两个元素相同,我怎样才能在元组中添加第三个元素? 在列表中,我们有三个元组,前两个相同的元素6220586。 因此,我们需要创建一个新的单个元组,如[(6220,586,(5+5+5))]

list = [(6220, 586, 5), (7032, 621, 0), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5)]

预期产出:

[(6220, 586, 15),(7032, 621, 0),(7030, 589, 0)]

到目前为止,我已经提出以下建议:

a_b=[]
for x in lst:
    for y in lst:
        if len(a_b) == 0:
            a_b.append((x[0],x[1],x[2]))
        if x[0]==y[0] and x[1]==y[1]:
                if (x[0],x[1],x[2]+y[2]) not in a_b:
                    t=(x[0],x[1],x[2]+y[2])
                    a_b.append(t)

4 个答案:

答案 0 :(得分:2)

您可以使用简单的整数聚合(defaultdict可以缩短整数):

from collections import defaultdict                        
agg = defaultdict(int)                                     
for item in lst:                                           
    agg[item[:2]] += item[2]   

result = [(k[0], k[1], v,) for k, v in agg.iteritems()]

结果:

[(6220, 586, 15), (7032, 621, 0), (7030, 589, 0)]

答案 1 :(得分:0)

如果订单很重要,我会让OrderedCounter对货币对进行求和,然后将货币对与价值组合起来:

>>> from collections import OrderedDict, Counter
>>> l1= [(6220, 586, 5), (7032, 621, 0), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5)]
>>> class OrderedCounter(Counter, OrderedDict):
...     pass
...
>>> oc = OrderedCounter()
>>> for a,b,c in l1:
...     oc[a,b] += c
...
>>> oc
OrderedCounter([((6220, 586), 15), ((7032, 621), 0), ((7030, 589), 0)])

最后:

>>> result = [k+(v,) for k,v in oc.items()]
>>> result
[(6220, 586, 15), (7032, 621, 0), (7030, 589, 0)]
>>>

如果顺序无关紧要,那么普通的Counter就足够了。

答案 2 :(得分:0)

from collections import defaultdict

d = defaultdict(int)
list_ = [(6220, 586, 5), (7032, 621, 0), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5)]

for l in list_:
    d[l[0:2]] += l[-1]
#defaultdict(int, {(6220, 586): 15, (7030, 589): 0, (7032, 621): 0})
[tuple(list(k) + [v]) for k, v in d.items()]

出:

    [(6220, 586, 15), (7032, 621, 0), (7030, 589, 0)]

答案 3 :(得分:0)

这是一个功能性编程经典!这是:

from itertools import groupby
from functools import reduce

lst = [(6220, 586, 5), (7032, 621, 0), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5), (7030, 589, 0), (7032, 621, 0), (6220, 586, 5)]

ab = []
for k, v in groupby(sorted(lst), lambda t: (t[0], t[1])):
    ab.append(reduce(lambda x, y: (x[0], x[1], x[2] + y[2]), v))

print(ab)

>>>
[(6220, 586, 15), (7030, 589, 0), (7032, 621, 0)]