返回/打印第一个数字超过20,最后一个数字超过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

输出符合预期,但我希望只有第一个和最后一个超过 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,例如,

有关模块内置函数的帮助 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))

最新更新