Reputation: 29
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?
Upvotes: 1
Views: 66
Reputation: 164713
max
for highest value onlyFor 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
for highest n valuesIf 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')
Upvotes: 0
Reputation: 80
Try this:
keys = ['a', 'b', 'c', 'd']
values = [80, 90, 70, 60]
print keys[values.index(max(values))]
Upvotes: 0
Reputation: 1267
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.
Upvotes: 1
Reputation: 278
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
Upvotes: 0