Solved

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

Posted on 2015-01-22
1
128 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
1 Comment
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

728 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now