【问题标题】:How to achieve python's any() with a custom predicate?如何使用自定义谓词实现 python 的 any()?
【发布时间】:2013-07-24 06:10:35
【问题描述】:
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> if filter(lambda x: x > 10, l):
...     print "foo"
... else:                     # the list will be empty, so bar will be printed
...     print "bar"
... 
bar

我想改用any(),但any() 只接受一个参数:可迭代。有没有更好的办法?

【问题讨论】:

    标签: python python-2.7 functional-programming any filterfunction


    【解决方案1】:

    使用generator expression 作为参数:

    any(x > 10 for x in l)
    

    这里的谓词在生成器表达式的表达式侧,但你可以在那里使用任何表达式,包括使用函数。

    演示:

    >>> l = range(10)
    >>> any(x > 10 for x in l)
    False
    >>> l = range(20)
    >>> any(x > 10 for x in l)
    True
    

    生成器表达式将被迭代直到any() 找到True 结果,并且不再进一步:

    >>> from itertools import count
    >>> endless_counter = count()
    >>> any(x > 10 for x in endless_counter)
    True
    >>> # endless_counter last yielded 11, the first value over 10:
    ...
    >>> next(endless_counter)
    12
    

    【讨论】:

      【解决方案2】:

      any() 中使用生成器表达式:

      pred = lambda x: x > 10
      if any(pred(i) for i in l):
          print "foo"
      else:
          print "bar"
      

      这假设您已经有了一些要使用的谓词函数,当然如果它像这样简单,您可以直接使用布尔表达式:any(i > 10 for i in l)

      【讨论】:

        猜你喜欢
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-15
        • 1970-01-01
        相关资源
        最近更新 更多