kkirsche
kkirsche

Reputation: 1257

Find key value of python list for use with other arrays

I'm currently working on a python program which does a number of calculations using 3 different arrays. The values of the array at each key (i.e. i[1] is related to a[1] which is also related to q[1].

I am trying to find out which value of q is highest (I was using python's q.max() function), but I don't know how to find out the value of the key for that max value. I.e. if the max is q[67] and is equal to 111110029233 how would I get the [67] value so that I can use that key to find the corresponding values in the i list and in a list.

Upvotes: 2

Views: 5908

Answers (5)

Blckknght
Blckknght

Reputation: 104762

It sounds like your ultimate goal is to find the a and i values that produce the largest q value. Currently you're trying to find the index of that maximum q so you can use it to access the corresponding values in i and a, but I think it is more efficient to go about it in a different way.

max_q, max_i, max_a = max(zip(q, i, a))

This finds the maximum q, value, and the corresponding i and a values. Here's how it works:

First the zip function constructs a generator (or list, if you're using Python 2) of tuples of matched values from each of the lists. That is, it yields (q[0], i[0], a[0]) followed by (q[1], i[1], a[1]) and so on.

Then the max function will compare the tuples, using the first value (from q) as the most significant piece. If there is a unique maximum value in q, this will be it. If there is a tie for maximum, the code I wrote above will prefer the one with the highest i value, and if that is tied, the one with the highest a value.

Finally, it unpacks the maximum tuple into max_q, max_i and max_a variables so you can use them individually.

Upvotes: 0

Serdalis
Serdalis

Reputation: 10489

max will not return the index, to find it you will have to do a loop through the list like so:

q = [1,2,3,4,5,6,5,4,3,2,1]

def find_max(li):
    max_item = max(li)
    return (li.index(max_item), max_item)

print find_max(q)

You can then use the first element in the returned value to access the related elements in your lists.

Alternatively if you only want the index you can use:

q.index(max(q))

as answered in This Stack overflow Answer

Upvotes: 2

Vader
Vader

Reputation: 3883

>>> q = [1,2,3,4,5,6,5,4,3,2,1]
>>> q.index(max(q))
5

Upvotes: 3

Loren Abrams
Loren Abrams

Reputation: 1002

q = [1,2,3,4,5,100,-1,0]
index = max(enumerate(q), key=lambda x: x[1])[0]

Upvotes: 1

Bula
Bula

Reputation: 1586

Try this:

import operator
max(enumerate(q),key=operator.itemgetter(1))[0]

Upvotes: 3

Related Questions