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