Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - list operations

Tags:

python

list

Given a list of unsorted numbers, I want to find the smallest number larger than N (if any).

In C#, I'd do something like this (checks omitted) :

var x = list.Where(i => i > N).Min();

What's a short, READABLE way to do this in Python?

like image 389
Cristian Diaconescu Avatar asked Jul 19 '10 14:07

Cristian Diaconescu


3 Answers

>>> l = [4, 5, 12, 0, 3, 7]
>>> min(x for x in l if x > 5)
7
like image 200
SilentGhost Avatar answered Nov 08 '22 06:11

SilentGhost


min(x for x in mylist if x > N)
like image 4
Daniel Stutzbach Avatar answered Nov 08 '22 06:11

Daniel Stutzbach


Other people have given list comprehension answers. As an alternative filter is useful for 'filtering' out elements of a list.

min(filter(lambda t: t > N, mylist))
like image 3
Donald Miner Avatar answered Nov 08 '22 08:11

Donald Miner