如何映射字符串列表和整数列表并查找具有最大价值的字符串 [英] How to map a list of strings and list of integers and find the string that has greatest value
问题描述
我为此感到烦恼.我有两个清单
I have been troubles by this. I have two lists
lista = ["a", "b", "c", "d"]
listb = [80, 90, 70, 60]
我想这样映射 "a"的值为80 "b"的值为90 "c"的值为70,并且 "d"的值为60 然后,我要打印具有最大值和第二大值的字符串.
I want to map it so "a" has a value of 80 "b" has a value of 90 "c" has a value of 70 and "d" has a value of 60 Then, I want to print the string that has the largest value and the second largest value.
有没有办法做到这一点?
Is there any way to do this?
推荐答案
max
仅用于最高价值
对于您的结果,您不需要一个明确的映射,例如通过字典.您可以计算出最高的 index 值,然后将其应用于您的密钥列表:
max
for highest value only
For your result, you don't need an explicit mapping, e.g. via a dictionary. You can calculate the index of the highest value and then apply this to your key list:
lista = ["a", "b", "c", "d"]
listb = [80, 90, 70, 60]
# a couple of alternatives to extract index with maximum value
idx = max(range(len(listb)), key=lambda x: listb[x]) # 1
idx, _ = max(enumerate(listb), key=lambda x: x[1]) # 1
maxkey = lista[idx] # 'b'
heapq
获取最高 n 值
如果您想获得最大的 n 值,则无需进行完整排序.您可以使用heapq.nlargest
:
heapq
for highest n values
If you want to the highest n values, a full sort is not necessary. You can use heapq.nlargest
:
from heapq import nlargest
from operator import itemgetter
n = 2
# a couple of alternatives to extract index with n highest values
idx = nlargest(n, range(len(listb)), key=lambda x: listb[x]) # [1, 0]
idx, _ = zip(*nlargest(n, enumerate(listb), key=lambda x: x[1])) # (1, 0)
maxkeys = itemgetter(*idx)(lista) # ('b', 'a')
这篇关于如何映射字符串列表和整数列表并查找具有最大价值的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!