我有一个数字数组,例如“ 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
Run Code Online (Sandbox Code Playgroud)
输出与预期的一样,但我想仅获得第一个和最后一个超过20的数字,而没有其余的数字。我意识到这对于大多数新手来说可能微不足道
您可以从生成器表达式中检查第一个,例如
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
另外,如果您不确定num
要搜索的对象是否不在迭代器中,则可以default
从中返回一个值,next
而不用StopIteration
像这样引发它:
模块内置模块中有关内置函数的帮助:
下一个(...)
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)