Solved

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

Posted on 2015-01-22
1
150 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: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
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 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 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…

632 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