1

In the List of tuples, add the 2nd element if the first and last element matches with the other tuples.

    p =[(u'basic', 7698, '01-2017'),
    (u'basic', 7685, '01-2017'),
    (u'Gross', 4875.0, u'01-2017'),
    (u'Gross', 4875.0, u'01-2017')]

And the output should be like

    [(u'basic',15383,'01-2017'),(u'Gross', 9750.0, u'01-2017')]

I'm trying to do this way

   o=[]        
   for i in p:
     if i[2] not in o:
        o.append(i[2])
     if i[0] not in o:
        o.append(i[0])
   count +=i[1]
   o.append(count)

my o/p:

   ['01-2017', 'basic', u'Gross', 53050.0, 4875.0]

3 Answers3

1

You could use a defaultdict to handle this. Use the first and last elements of the tuple as a key and the second as the value, which is accumulated by addition:

from collections import defaultdict

l = [(u'basic', 7698, '01-2017'),
     (u'basic', 7685, '01-2017'),
     (u'Gross', 4875.0, u'01-2017'),
     (u'Gross', 4875.0, u'01-2017')]

d = defaultdict(int)
for t in l:
    d[(t[0], t[-1])] += t[1]

# create list of tuples from the defaultdict values
result = [(k[0], d[k], k[1]) for k in d]

>>> print(result)
[(u'basic', 15383, '01-2017'), (u'Gross', 9750.0, u'01-2017')]
mhawke
  • 84,695
  • 9
  • 117
  • 138
0
from collections import defaultdict

l = [(u'basic', 7698, '01-2017'),
     (u'basic', 7685, '01-2017'),
     (u'Gross', 4875.0, u'01-2017'),
     (u'Gross', 4875.0, u'01-2017'),
     (u'basic', 7685, '01-2017'),]

# make a list of tuples of 1st and 3rd elements
r = [(x, z) for x, y, z in l]

# this is based on
# https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list
r_sorted = [(y,x[1]) for (y, x) in sorted(zip(r, l), key=lambda pair: pair[0])]

# this is based on
# https://stackoverflow.com/questions/18194712/how-do-i-sum-tuples-in-a-list-where-the-first-value-is-the-same
# as per @Idles dublication alert
testDict = defaultdict(int)
for key, val in r_sorted:
    testDict[key] += val

print(testDict.items())
0

You can also use itertools.groupby for this :

from itertools import groupby

p =[(u'basic', 7698, '01-2017'),
    (u'basic', 7685, '01-2017'),
    (u'Gross', 4875.0, u'01-2017'),
    (u'Gross', 4875.0, u'01-2017')]

[(grp[0], sum(val[1] for val in vals), grp[1]) 
    for grp, vals in groupby(p, key=lambda x: (x[0], x[2]))]

# [('basic', 15383, '01-2017'), ('Gross', 9750.0, '01-2017')]
Unatiel
  • 1,060
  • 1
  • 11
  • 17