如何映射字符串列表和整数列表,并找到具有最大值的字符串

问题描述 投票:1回答:4

我遇到了麻烦。我有两个清单

lista = ["a", "b", "c", "d"]
listb = [80, 90, 70, 60]

我想映射它,因此“a”的值为80“b”的值为90“c”的值为70,“d”的值为60然后,我想要打印出具有该值的字符串最大值和第二大值。

有没有办法做到这一点?

python string list sorting int
4个回答
0
投票

max for highest value only

对于您的结果,您不需要显式映射,例如通过字典。您可以计算最高值的索引,然后将其应用于您的密钥列表:

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 for highest n values

如果您想要最高n值,则不需要完整排序。你可以使用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')

1
投票

你可以做点什么

print(lista[listb.index(max(listb))])

它找到listb的最大数字索引,然后获取lista中相同索引的项目。

这应该工作,但我建议将来使用python dicts这类事情。


0
投票
keys = ['a', 'b', 'c', 'd']
values = [80, 90, 70, 60]
dictionary = dict(zip(keys, values))
print(dictionary)
{'a': 80, 'b': 90, 'c': 70, 'd': 60}

我想你可以尝试使用operator.itemgetter:

import operator
max(dictionary.iteritems(), key=operator.itemgetter(1))[0]

告诉我这是否有效


0
投票

试试这个:

keys = ['a', 'b', 'c', 'd']
values = [80, 90, 70, 60]
print keys[values.index(max(values))]
© www.soinside.com 2019 - 2024. All rights reserved.