【问题标题】:How to map a list of strings and list of integers and find the string that has greatest value如何映射字符串列表和整数列表并找到具有最大价值的字符串
【发布时间】:2019-04-17 18:17:13
【问题描述】:

我一直为此烦恼。我有两个列表

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

我想这样映射它 "a" 的值为 80 “b”的值为 90 "c" 的值为 70 并且 “d”的值为 60 然后,我想打印具有最大值和第二大值的字符串。

有没有办法做到这一点?

【问题讨论】:

  • 您要求提供最大值和第二大值,但您接受的答案为您提供最大值。如果这是您的意图,请给予最大的尊重。否则,有些答案可以完全解决您的问题。
  • @gboffi,由于标题中的非常具体的问题,我的回答(部分)引起了混乱。我已经更新(通过heapq)来解决前n个答案(类似于你的,但使用itemgetter)。
  • @jpp 我的答案现在没用了→删除。

标签: python string list sorting int


【解决方案1】:

max 仅用于最高值

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

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

【讨论】:

  • 谢谢,但我想知道什么是枚举以及如何使用 lambda。它运行完美。
  • @Ragent,见 enumeratelambda
【解决方案2】:

试试这个:

keys = ['a', 'b', 'c', 'd']
values = [80, 90, 70, 60]
print keys[values.index(max(values))]

【讨论】:

  • 完整排序在这里效率低下,尤其是对于大量输入。
  • 你是对的,经过深思熟虑后,我将答案更改为更有效的解决方案
  • 这与@Qwerty 提出的解决方案完全相同(在编辑我的答案之前我没有看到 ir,抱歉)
【解决方案3】:

你可以做类似的事情

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

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

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

【讨论】:

  • 请注意,您在此解决方案中迭代 listb 两次,这不是绝对必要的。您可以在查找 max 时通过单次迭代提取索引,例如通过rangeenumerate
【解决方案4】:
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]

告诉我这是否有效

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多