如果前两个元素相同,如何将第三个元素添加到元组?
在列表中,我们有三个元组,其前两个相同的元素6220
和586
。
因此,我们需要创建一个新的单个元组,例如[(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)
最佳答案
如果顺序很重要,我将创建一个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
就足够了。