[英]How to find the highest value element in a list with reference to a dictionary on python
How do I code a function in python which can:我如何在 python 中编码 function 可以:
For example,例如,
Assume the function is called H_abs_W()
.假设 function 被称为H_abs_W()
。
Given the following list and dict:给定以下列表和字典:
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
Then calling the function as:然后调用 function 为:
H_abs_W(list_1,Dict_1)
Should give the output:应该给output:
'apples',10.46 '苹果',10.46
EDIT: I managed to do it in the end with the code below.编辑:我最终用下面的代码做到了。 Looking over the answers, turns out I could have done it in a shorter fashion, lol.查看答案,结果发现我可以用更短的方式完成,哈哈。
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])
try this,尝试这个,
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
you can use Counter
to calculate the frequency(number of occurrences) of each item in the list.您可以使用Counter
计算列表中每个项目的频率(出现次数)。
max(counter.values())
will give us the count of maximum occurring element max(counter.values())
将为我们提供最大出现元素的计数max(counter, key=counter.get)
will give the which item in the list is associated with that highest count. 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.