Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List - Searching for a value and its location

Tags:

python

list

I'm looking for the greatest number out of a list to then obtain the element 1 location before If anyone knows how to do this it would be very much appreciated.

my_list = ['room', 10, 'chamber', 23, 'kitchen', 8]

pos = my_list.aMethodToGetTheGreatestValuePosition()

print('The biggest room is ' + my_list[pos-1])
like image 440
Miloertas Avatar asked May 23 '26 02:05

Miloertas


1 Answers

This will do it without having to traverse the list multiple times:

my_list = ['room', 10, 'chamber', 23, 'kitchen', 8]

pos = max(enumerate(my_list[1::2]), key=lambda x: x[1])[0]

print('The biggest room is ' + my_list[2*pos])

This uses enumerate to get the indexes of my_list at the same time it is searching for the max.

Or you can be slightly clever with zip:

print('The biggest room is ' +  max(zip(*[iter(my_list)]*2), key=lambda x: x[1])[0])

which relies upon using the same iterator over my_list to feed successive values to zip (borrowed from another excellent answer). This essentially turns your flat list into a list of tuples which would be a nicer way of storing the original data, if you have that option:

>>> list(zip(*[iter(my_list)]*2))
[('room', 10), ('chamber', 23), ('kitchen', 8)]
like image 76
Turn Avatar answered May 24 '26 16:05

Turn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!