gpt4 book ai didi

Python,在(a,b)对列表中找到具有最大总和(b值)的a值

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:52 25 4
gpt4 key购买 nike

我在 python 中有一个二维列表。我想返回第二个值之和最大化的第一个维度的值。我不关心打破任何关系,我的第一个维度将始终是 1 到 6。

例如:

1)

list=[(1,200),(1,50),(2,275)]
should return 2 since 275 > 250

2)

list= [(1,100),(2,50),(2,300),(1,1000)
should return 1 since 1100 > 350

我尝试的解决方案可行但不是最优的(理想情况下 id 就像一个短的 1-3 行解决方案)并且使用我的第一个维度将仅为值 1-6 的事实。我想要一些更干净的东西。

#for each element 1 through 6
For i in range(len(list)):
if list[i][0]=1:
#do this for oneSum, twoSum, etc, and take the largest sum
oneSum+=list[i][1]

最佳答案

关于:

def foo(lst):
d = {}
for (k,v) in lst: d[k] = d.get(k,0) + v # Accumulate
return max(d.items(), key=lambda x:x[1])[0] # Find max value, return corresponding key

print foo([(1,200),(1,50),(2,275)]) # 2
print foo([(1,100),(2,50),(2,300),(1,1000)]) # 1

或者如果你想要 key 和总和:

def foo(lst):
d = {}
for (k,v) in lst: d[k] = d.get(k,0) + v # Accumulate
return max(d.items(), key=lambda x: x[1]) # Find max value, return corresponding tuple

print foo([(1,200),(1,50),(2,275)]) # (2, 275)
print foo([(1,100),(2,50),(2,300),(1,1000)]) # (1, 1100)

关于Python,在(a,b)对列表中找到具有最大总和(b值)的a值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28921334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com