[英]How to print the key of highest value from the list's element of the dictionary?
[英]How to find the highest value element in a list with reference to a dictionary on python
我如何在 python 中编码 function 可以:
例如,
假设 function 被称为H_abs_W()
。
给定以下列表和字典:
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
然后调用 function 为:
H_abs_W(list_1,Dict_1)
应该给output:
'苹果',10.46
编辑:我最终用下面的代码做到了。 查看答案,结果发现我可以用更短的方式完成,哈哈。
def H_abs_W(list_1,Dict_1):
freqW = {}
for char in list_1:
if char in freqW:
freqW[char] += 1
else:
freqW[char] = 1
ASum_W = 0
i_word = ''
for a,b in freqW.items():
x = 0
d = Dict_1.get(a,0)
x = abs(float(b)*float(d))
if x > ASum_W:
ASum_W = x
i_word = a
return(i_word,ASum_W)
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
d = {k:0 for k in list_1}
for x in list_1:
if x in Dict_1.keys():
d[x]+=Dict_1[x]
m = max(Dict_1, key=Dict_1.get)
print(m,Dict_1[m])
尝试这个,
key, value = sorted(Dict_1.items(), key = lambda x : x[1], reverse=True)[0]
print(f"{key}, {list_1.count(key) * value}")
# apples, 10.46
您可以使用Counter
计算列表中每个项目的频率(出现次数)。
max(counter.values())
将为我们提供最大出现元素的计数max(counter, key=counter.get)
将给出列表中与最高计数相关联的项目。==================================================== =======================
from collections import Counter
def H_abs_W(list_1, Dict_1):
counter = Counter(list_1)
count = max(counter.values())
item = max(counter, key=counter.get)
return item, abs(count * Dict_1.get(item))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.