I am trying to find the N biggest values from a list, and then print out their positions in the list.
If I would only focus on the max. value, it would look like this:
>>>>fr = [8,4,1,1,12]
>>>>print fr.index(max(fr))
4
However, my aim is to get an output like: 4,0,1
if it were for n=3. The 0
here shows the position of the second biggest value. REMEMBER, I am not interested in the value, but in their position!
The max() method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument. The index() method is used to find the index of a given element from a python list.
Python – Find Index or Position of Element in a List. To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.
The max() function prints the largest element in the list.
i = 0 N = int(input('How many numbers do you want to enter?: ')) if N>0: n_maximum = int(input('Insert the first number: ')) while i < N-1: n=int(input('Insert a number: ')) if n > n_maximum: n_maximum = n; i += 1 print('The maximum value is: ', n_maximum) else: print('You must enter a quantity of at least one!
Use heapq.nlargest
with key = fr.__getitem__
:
>>> import heapq
>>> fr = [8,4,1,1,12]
>>> heapq.nlargest(3, xrange(len(fr)), key=fr.__getitem__)
[4, 0, 1]
If you want the values itself, then:
>>> heapq.nlargest(3, fr)
[12, 8, 4]
Another way is:
[fr.index(x) for x in sorted(fr, reverse=True)[:3]]
When we compare speed of both of them...
import heapq
fr = [8, 4, 1, 1, 12]
def method_one():
for i in xrange(10000):
res = [fr.index(x) for x in sorted(fr, reverse=True)[:3]]
def method_two():
for i in xrange(10000):
heapq.nlargest(3, xrange(len(fr)), key=fr.__getitem__)
if __name__ == '__main__':
import timeit
print timeit.repeat(stmt='method_one()',
setup='from __main__ import method_one',
number=100)
print timeit.repeat(stmt='method_two()',
setup='from __main__ import method_two',
number=100)
we get:
[1.1253619194030762, 1.1268768310546875, 1.128382921218872]
[2.5129621028900146, 2.529547929763794, 2.492828130722046]
This simplest way is to just do this
>>> fr = [8,4,1,1,12]
>>> n = 3
>>> result = [fr.index(i) for i in sorted(fr, reverse=True)][:n]
>>> print(result)
[4, 0, 1]
No libraries and dependancies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With