简体   繁体   中英

Return / print first number to be over 20, and last number to be over 20

I have an array of numbers such as '17.2, 19.1, 20.4, 47.5, 34.2, 20.1, 19'

Trying to figure out a way to pick the first number to be over 20 (and none following) and the last number to be over 20 before falling below.

So far I've only tried to pick numbers between 20 and 23, but it's not ideal (see code for example)

nums = [15, 16.2, 17.1, 19.7, 20.2, 21.3, 46.2, 33.7, 27.3, 21.2, 20.1, 19.6]
test_lst = [x for x in nums if x >=20 and x<=23]
print test_lst

The output is as expected, but i'd like to have just the first and last number that first go over 20, without the rest. I realize this is probably trivial for most, newish to python

You could check the first one from a generator expression like,

>>> nums
[15, 16.2, 17.1, 19.7, 20.2, 21.3, 46.2, 33.7, 27.3, 21.2, 20.1, 19.6]
>>> next(x for x in nums if x > 20) # first one from front
20.2
>>> next(x for x in reversed(nums) if x > 20) # first one from rear
20.1
>>> 

Also, if you are not sure the num you are searching is not there in the iterable, you could return a default value from next rather than have it raise StopIteration like,

Help on built-in function next in module builtins:

next(...)

 next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
>>> x
[1, 2, 3]
>>> next((x for x in x if x > 20), 0) # if no number > 20 is found, return 0
0
nums = [15, 16.2, 17.1, 19.7, 20.2, 21.3, 46.2, 33.7, 27.3, 21.2, 20.1, 19.6] def first_over_20(nums): for num in nums: if num > 20: return num def last_over_20(nums): for num in nums[::-1]: if num > 20: return num print(first_over_20(nums)) print(last_over_20(nums))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM