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

实际输出:[1,3,5,6] 预期输出:[1,3,5]

如何在两个列表上实现布尔AND操作(列表交集)?


当前回答

你也可以使用计数器!它不会保留顺序,但会考虑副本:

>>> from collections import Counter
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> d1, d2 = Counter(a), Counter(b)
>>> c = [n for n in d1.keys() & d2.keys() for _ in range(min(d1[n], d2[n]))]
>>> print(c)
[1,3,5]

其他回答

使用过滤器和lambda运算符可以实现函数式的方法。

list1 = [1,2,3,4,5,6]

list2 = [2,4,6,9,10]

>>> list(filter(lambda x:x in list1, list2))

[2, 4, 6]

编辑:它过滤掉了同时存在于list1和list中的x,集差异也可以使用:

>>> list(filter(lambda x:x not in list1, list2))
[9,10]

python3 filter返回一个过滤器对象,用list封装它返回输出列表。

这是一个示例,当您需要在结果中的每个元素出现的次数应该与它在两个数组中显示的次数相同。

def intersection(nums1, nums2):
    #example:
    #nums1 = [1,2,2,1]
    #nums2 = [2,2]
    #output = [2,2]
    #find first 2 and remove from target, continue iterating

    target, iterate = [nums1, nums2] if len(nums2) >= len(nums1) else [nums2, nums1] #iterate will look into target

    if len(target) == 0:
            return []

    i = 0
    store = []
    while i < len(iterate):

         element = iterate[i]

         if element in target:
               store.append(element)
               target.remove(element)

         i += 1


    return store

如果你将两个列表中较大的一个转换为一个集合,你可以使用intersection()获得该集合与任何可迭代对象的交集:

a = [1,2,3,4,5]
b = [1,3,5,6]
set(a).intersection(b)
a = [1,2,3,4,5]
b = [1,3,5,6]
c = list(set(a).intersection(set(b)))

应该像做梦一样工作。并且,如果可以的话,使用集合而不是列表来避免所有这些类型更改!

如果布尔与是指同时出现在两个列表中的项,例如交集,那么你应该看看Python的set和frozenset类型。