【问题标题】:or boolean function as function argument或布尔函数作为函数参数
【发布时间】:2014-07-02 14:35:06
【问题描述】:

给定

a = [1, 2, 3, 4]
b = [10, 1, 20, 30, 4]

我想检查a 中的任何元素是否存在于b 中。

>>> [i in b for i in a]
Out[45]: [True, False, False, True]

上面的代码完成了部分工作。下一步可能是reduce。 但是,如果没有我自己的 or 函数实现,我无法让下面的代码正常工作。

def is_any_there(a, b):
    one_by_one = [i in b for i in a]

    def my_or(a,b):
        if a or b:
            return True
        else:
            return False
    return reduce(my_or, one_by_one)

如何避免or函数的重写?

【问题讨论】:

  • 你可以把它变成一个相当短的 lambda:reduce(lambda x,y: x or y, one_by_one),但 any 确实是你想要使用的。

标签: python list boolean boolean-operations


【解决方案1】:

is_there_any 只是重新实现了any 函数,从 Python 2.5 开始可用:

any(x in b for x in a)

此外,my_or 已经在标准库中作为operator.or_ 提供。

【讨论】:

    【解决方案2】:

    如果项目是可散列的,那么你可以使用set.isdisjoint():

    >>> a = [1, 2, 3, 4]
    >>> b = [10, 1, 20, 30, 4]
    >>> not set(a).isdisjoint(b)
    True
    >>> b = [10, 10, 20, 30, 40]
    >>> not set(a).isdisjoint(b)
    False
    

    【讨论】: