Python Forum
finding 2 max values in an array in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
finding 2 max values in an array in python
#12
There is also heapq for finding nlargest and nsmallest values.

From Python Cookbook, 3rd Edition by David Beazley; Brian K. Jones, O'Reilly Media 2013:

Quote:The nlargest() and nsmallest() functions are most appropriate if you are trying to find a relatively small number of items. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max(). Similarly, if N is about the same size as the collection itself, it is usually faster to sort it first and take a slice (i.e., use sorted(items)[:N] or sorted(items)[-N:]). It should be noted that the actual implementation of nlargest() and nsmallest() is adaptive in how it operates and will carry out some of these optimizations on your behalf (e.g., using sorting if N is close to the same size as the input).

Borrowing nilamo's lambda it can be expressed:

>>> import heapq
>>> lst = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> heapq.nlargest(2, enumerate(lst), key=lambda x: x[1])
[(8, 42), (9, 37)]
Or:

>>> heapq.nlargest(2, [(v, i) for i, v in enumerate(lst)])
>>> [(42, 8), (37, 9)]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: finding 2 max values in an array in python - by perfringo - Oct-18-2018, 09:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create array of values from 2 variables paulo79 1 1,082 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  Creating a numpy array from specific values of a spreadsheet column JulianZ 0 1,114 Apr-19-2022, 07:36 AM
Last Post: JulianZ
  Calculate next rows based on previous values of array divon 0 1,760 Nov-23-2021, 04:44 AM
Last Post: divon
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,101 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Finding an element in a 1d list in a 2d array lionrocker221 0 1,816 Jun-27-2020, 04:50 PM
Last Post: lionrocker221
  Finding Max and Min Values Associated with Unique Identifiers in Python ubk046 1 2,042 May-08-2020, 12:04 PM
Last Post: anbu23
  Finding nearest point of a Multidigraph in Python 3.7 stixmagiggins 5 3,746 Aug-24-2019, 08:51 AM
Last Post: ThomasL
  Help with finding correct topic in Python learning yahya01 1 2,191 Jun-06-2019, 05:01 PM
Last Post: buran
  change array column values without loop khalidreemy 2 3,767 May-05-2019, 09:05 AM
Last Post: DeaD_EyE
  finding problems connecting python to sqlite Dennis 1 2,279 Dec-10-2018, 02:58 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020