[英]Python - How to check if the next value in a list is the same as the previous?
[英]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]]
如果前兩個值是相同的和第三個值並將新項目保存在一個新列表中,如下所示: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]]
或者...
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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.