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操作(列表交集)?
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操作(列表交集)?
当前回答
使用过滤器和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封装它返回输出列表。
其他回答
这样可以得到两个列表的交集,也可以得到公共重复项。
>>> from collections import Counter
>>> a = Counter([1,2,3,4,5])
>>> b = Counter([1,3,5,6])
>>> a &= b
>>> list(a.elements())
[1, 3, 5]
a = [1,2,3,4,5]
b = [1,3,5,6]
c = list(set(a).intersection(set(b)))
应该像做梦一样工作。并且,如果可以的话,使用集合而不是列表来避免所有这些类型更改!
当我们使用tuple时,我们想要交叉
a=([1,2,3,4,5,20], [8,3,9,5,1,4,20])
for i in range(len(a)):
b=set(a[i-1]).intersection(a[i])
print(b)
{1, 3, 4, 5, 20}
这是一个示例,当您需要在结果中的每个元素出现的次数应该与它在两个数组中显示的次数相同。
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
对我来说,使用列表推导式是一个非常明显的方法。不确定性能如何,但至少能保持列表。
[x for x in a if x in b]
或者"所有在A中的x值,如果x值在B中"