简体   繁体   English

返回/打印第一个数字超过 20,最后一个数字超过 20

[英]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'我有一个数字数组,例如'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.试图找出一种方法来选择第一个超过 20 的数字(并且没有跟随)和最后一个超过 20 的数字,然后再跌破。

So far I've only tried to pick numbers between 20 and 23, but it's not ideal (see code for example)到目前为止,我只尝试选择 20 到 23 之间的数字,但这并不理想(参见代码示例)

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. output 符合预期,但我只想拥有第一个和最后一个数字,即第一个 go 超过 20,没有 rest。 I realize this is probably trivial for most, newish to python我意识到这对大多数人来说可能是微不足道的,对 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,此外,如果您不确定要搜索的num不在可迭代对象中,您可以从next返回一个default值,而不是像这样引发StopIteration

Help on built-in function next in module builtins:内置模块内置 function 的帮助:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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