我有(a,b)对的python列表,我想构建一个函数,它返回一个具有最高计数的值。如果存在任何联系,则将相关的b值相加并返回其对应的b具有最低总和的值。
示例:
getMostFrequent([(1,3),(1,4),(2,5),(3,6))= 1
getMostFrequent([(1,3),(1,4),(2,5),(2,6)])= 1(因为3 + 4 <5 + 6)
到目前为止我的工作:
我有2个函数,一个获得最高计数(无关系),另一个对相应的值求和b值。我在组合它们时遇到了麻烦,这样我就可以打破平局,然后总结b值来打破平局。
lst=[twodlst[i][0] for i in range(len(twodlst))]
def most_common():
return max(set(lst), key=lst.count)
def getAns(listofwinnersandconfidence):
for i in range(len(listofwinnersandconfidence)):
anschoice=listofwinnersandconfidence[i][0]
d = {}
for (k,v) in listofwinnersandconfidence: d[k] = d.get(k,0) + v
return min(d.items(), key=lambda x:x[1]) # Find min value, return corresponding key
答案 0 :(得分:2)
使用字典存储a
- &gt; [ count(a), -sum(b) ]
;然后你可以从字典中获取最大数量的项目;我在这里使用itemgetter
而不是lambda函数。请注意,我否定sum(b)
,以便该值的最大值产生所需的最小值;)
from collections import defaultdict
from operator import itemgetter
entries = [(1,3),(1,4),(2,5),(2,6)]
counters = defaultdict(lambda: [0, 0])
for a, b in entries:
# if a was not in dictionary yet, it will get
# initialized to a list [0, 0]
counts = counters[a]
counts[0] += 1 # count the a's
counts[1] -= b # count the 0 - sum(b's)
# items will be `[(1, [2, -7]), (2, [2, -11])]`;
# we take the [1] of them for key, thus we select maximum of
# [2, -7] and [2, -11]; then we take the [0] of the item
# tuple to get the key, i.e. a.
max_a = max(counters.items(), key=itemgetter(1))[0]
print(max_a)