Solved

easy way to get the second (third, ...)  largest number in python

Posted on 2015-01-22
1
146 Views
Last Modified: 2015-01-27
Hi experts,

Is there an easy way in Python to get the second, or the third largest number in an array? consider two cases, one is every number is different, the other case is there are possible duplicated numbers.

Looking at some similar from MS Excel as: large(A:A, 2) to get the second largest number in A column.

Thanks,
RDB
0
Comment
Question by:ResourcefulDB
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40565608
Here you go:

nth_largest = lambda l, nth: sorted(set(l))[-(nth if nth<=len(set(l)) and nth>=1 else 0)]
print(nth_largest( (9, 8, 8, 8, 9, 9, 9, 3, 3, 4), 2))   # return the second largest number in the list - 8

Open in new window


You didn't define what you want to happen if you ask for the 4th largest number but only have 3 unique numbers, I went with the smallest number.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
run a set of files in Python 2 72
linux crontab output 3 83
python error - set 2 59
Cannot connect to Oracle database, python not recognizing cx_Oracle 2 71
"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question