![](/img/trans.png)
[英]How to sort a list of tuples by the first element in each tuple, and pick the tuple with the largest last element in each group
[英]Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple
因此,如果我有一個名為的列表:
d = [('hey',7),('hey',7),('hello',8)]
我如何使它輸出:
d = [('hey',14),('hello',8)]
使用itertools.groupby
和operator.itemgetter
[(k, sum(map(itemgetter(1), g))) for k, g in groupby(sorted(d), itemgetter(0))]
印刷:
[('hey', 14), ('hello', 8)]
lst = [('hey', 7), ('hey', 7), ('hello', 8)]
用:
d = {x:0 for x, y in lst}
for text, num in lst:
d[text] = d[text] + num
new_lst = list(d.items())
print(new_lst)
對於沒有任何地圖或導入功能的簡單使用:
s = {x[0] for x in lst}
new_lst = [(i,sum(x[1] for x in lst if x[0] == i)) for i in s]
print(new_lst)
或者
s = []
for i in lst:
if i[0] not in s:
s.append(i[0])
new_lst = []
for i in s:
m=[]
for x in lst:
if x[0] == i:
m.append(x[1])
tmp = (i,sum(m))
new_lst.append(tmp)
print(new_lst)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.