简体   繁体   中英

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]]

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]]

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM