khosro parichehreh
khosro parichehreh

Reputation: 23

How to check same value in list in list python

inp = [['t', 80, 500.0], ['g', 135, 1500.0], ['t', 80, 8000.0],['g', 170, 1500.0],['g', 135, 1000.0]]

If first two values are the same sum 3rd value and save new items in a new list like this: inp1 = [['t', 80, 8500.0], ,['g', 170, 1500.0],['g', 135, 2500.0]]

Upvotes: 1

Views: 73

Answers (2)

AirSquid
AirSquid

Reputation: 11938

Alternatively...

In [19]: temp = defaultdict(int)                                                

In [20]: for i, j, k in inp: 
    ...:     temp[(i,j)] += k 
    ...:                                                                        

In [21]: res = [[*t[0], t[1]] for t in temp.items()]                            

In [22]: res                                                                    
Out[22]: [['t', 80, 8500.0], ['g', 135, 2500.0], ['g', 170, 1500.0]]

Upvotes: 1

Andreas
Andreas

Reputation: 9207

inp = [['t', 80, 500.0], ['g', 135, 1500.0], ['t', 80, 8000.0],['g', 170, 1500.0],['g', 135, 1000.0]]

dic = {x+"-"+str(y):z for (x,y,z) in inp}
inp1 = [x[0].split("-") + [sum([n[2] for n in inp if x[0]==n[0]+"-"+str(n[1])])] for x in dic.items()]

print(inp1)
# [['t', '80', 8500.0], ['g', '135', 2500.0], ['g', '170', 1500.0]]

Upvotes: 1

Related Questions