为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2021-08-17 18:48:47
我一直为此烦恼。我有两个清单lista = ["a", "b", "c", "d"]listb = [80, 90, 70, 60]我想映射它,所以 "a" 的值为 80 "b" 的值为 90 "c" 的值为 70,"d" 的值为 60 然后,我想打印具有最大值和第二大值。有没有办法做到这一点?
查看完整描述

3 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

max 只为最高价值

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


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:


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')


查看完整回答
反对 回复 2021-08-17
?
HUX布斯

TA贡献1876条经验 获得超6个赞

你可以做类似的事情

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

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

这应该有效,但是我建议将来使用 python dicts 来处理这种事情。


查看完整回答
反对 回复 2021-08-17
?
萧十郎

TA贡献1815条经验 获得超13个赞

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]

告诉我这是否有效


查看完整回答
反对 回复 2021-08-17
  • 3 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号