Skip to main content
 首页 » 编程设计

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

2025年05月04日16sharpest

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

试图找出一种方法来选择第一个超过 20 的数字(后面没有一个)和最后一个超过 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 

输出符合预期,但我希望只有第一个和最后一个超过 20 的数字,没有其他数字。我意识到这对大多数 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 之类的,

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