如何在 python 中对数组执行逻辑函数

How to do logical functions on arrays in python

是否有可能以某种方式在数组上执行逻辑函数,例如

a= [1,2,3,4,5,6]
b= [1,3,5,7]
c= a and b

resulting in c=[1,3,5]

所以只有两个数组中都存在的值。

相同或例如:

d = a OR b 

resulting in b=[1,2,3,4,5,6,7]

这在 python 中是否可能以某种方式实现,或者是否有短函数? 感谢您的回复

列表不支持逻辑运算,但您可以在集合中进行:

a= [1,2,3,4,5,6]
b= [1,3,5,7]

c = list(set(a) | set(b))

d = list(set(a) & set(b))

print(c)
# OUTPUT: [1, 2, 3, 4, 5, 6, 7]
print(d)
# OUTPUT: [1, 3, 5]

如果您的集合包含唯一值,您可能应该使用 python set。它们实际上是数学集合:https://en.wikipedia.org/wiki/Set_(mathematics)并支持集合的一般操作,例如intersectionunion

>>> a = {1, 2, 3, 4, 5, 6}
>>> b = {1, 3, 5, 7}
>>> c = a.intersection(b)
>>> c
{1, 3, 5}

这是您的代码片段:

def and_array(a, b):
    return [a[i] for i in range(min(len(a), len(b))) if a[i] in b or b[i] in a]
def or_array(a, b):
    return a + [element for element in b if not element in a]
    
a= [1,2,3,4,5,6]
b= [1,3,5,7]
c = and_array(a, b)
d = or_array(a, b)
print(c)
print(d)

结果:

[1, 2, 3]
[1, 2, 3, 4, 5, 6, 7]

它不是那么快,对于非常大的列表避免这种情况并使用 numpy 或内置函数!