0
votes

I'm writing a python script.

I have a list of numbers:

b = [55.0, 54.0, 54.0, 53.0, 52.0, 51.0, 50.0, 49.0, 48.0, 47.0, 45.0, 45.0, 44.0, 43.0, 41.0, 40.0, 39.0, 39.0, 38.0, 37.0, 36.0, 35.0, 34.0, 33.0, 32.0, 31.0, 30.0, 28.0, 27.0, 27.0, 26.0, 25.0, 24.0, 23.0, 22.0, 22.0, 20.0, 19.0, 18.0, 17.0, 16.0, 15.0, 14.0, 13.0, 11.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0]

I need to parse the list and see if the list contains '50'. If it does not,I have to search for one less number 49. if it is not there I have to look for 48. I can do this down to 47. In python, is there a one liner code I can do this, or can I use a lambda for this?

6
isn't it easier to find the MAX value that is lower or equal to 50 and higher than 46? You can do in in liner way or logarithmicDmitryK
if 50 in b and lowestValue = min(b) and maximumVal = max(b)Torxed

6 Answers

3
votes

You could use min() and abs():

>>> b = [55.0, 54.0, 54.0, 53.0, 52.0, 51.0, 50.0, 49.0, 48.0, 47.0, 45.0, 45.0, 44.0, 43.0, 41.0, 40.0, 39.0, 39.0, 38.0, 37.0, 36.0, 35.0, 34.0, 33.0, 32.0, 31.0, 30.0, 28.0, 27.0, 27.0, 26.0, 25.0, 24.0, 23.0, 22.0, 22.0, 20.0, 19.0, 18.0, 17.0, 16.0, 15.0, 14.0, 13.0, 11.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0]
>>> min(b, key=lambda x:abs(x-50))
50.0
>>> min(b, key=lambda x:abs(x-20.1))
20.0
3
votes
max(i for i in b if i <= 50)

It will raise a ValueError if there are no elements that match the condition.

2
votes
max(filter(lambda i: i<=50, b))

or, to handle list with all elements above 50:

max(filter(lambda i: i<=50, b) or [None])
1
votes

You can do this with a generator expression and max.

max(n for n in b if n >= 47 and n <= 50)
0
votes
highestValue = max(b)
lowestValue = min(b)
if 50 in b:
    pass

Three different ways of finding numbers, highest, lowest and if 50 is in the mix. And if you need to check if multiple numbers is in your hughe list, say you need to know if 50, 30 and 40 is in there:

set(b).issuperset(set([50, 40, 30])) 
0
votes

Oneliner without any lambda (raises ValueError if value not found):

max((x for x in b if 46 < x <= 50))

or version that returns None in this case:

from itertools import chain
max(chain((x for x in b if 46 < x <= 50), (None,)))