【问题标题】:Return / print first number to be over 20, and last number to be over 20返回/打印第一个数字超过 20,最后一个数字超过 20
【发布时间】:2019-10-17 14:49:10
【问题描述】:

我有一个数字数组,例如 '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 来说是新手

【问题讨论】:

标签: python math


【解决方案1】:

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

>>> 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 在模块 builtins 中的帮助:

下一个(...)

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

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2014-05-28
      • 2021-03-18
      • 1970-01-01
      • 2017-11-19
      • 2015-08-14
      相关资源
      最近更新 更多