简体   繁体   中英

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]

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?

You could do something like

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

It finds the maximum numbers index of listb , then gets the item of that same index in lista .

This should work, however I recommend using python dicts in the future for this kind of thing.

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}

I guess you could try using operator.itemgetter:

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

Tell me if this worked

max for highest value only

For your result, you don't need an explicit mapping, eg 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 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')

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM