繁体   English   中英

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

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

我有一个数字数组,例如'17.2、19.1、20.4、47.5、34.2、20.1、19'

试图找出一种方法来选择第一个超过 20 的数字(并且没有跟随)和最后一个超过 20 的数字,然后再跌破。

到目前为止,我只尝试选择 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

output 符合预期,但我只想拥有第一个和最后一个数字,即第一个 go 超过 20,没有 rest。 我意识到这对大多数人来说可能是微不足道的,对 python 来说是新的

您可以从生成器表达式中检查第一个,例如,

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

此外,如果您不确定要搜索的num不在可迭代对象中,您可以从next返回一个default值,而不是像这样引发StopIteration

内置模块内置 function 的帮助:

下一个(...)

 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