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操作(列表交集)?
当前回答
在这种情况下,你有一个列表的列表地图很方便:
>>> lists = [[1, 2, 3], [2, 3, 4], [2, 3, 5]]
>>> set(lists.pop()).intersection(*map(set, lists))
{2, 3}
适用于类似的迭代对象:
>>> lists = ['ash', 'nazg']
>>> set(lists.pop()).intersection(*map(set, lists))
{'a'}
如果列表是空的,Pop会爆炸,所以你可能想要在一个函数中进行包装:
def intersect_lists(lists):
try:
return set(lists.pop()).intersection(*map(set, lists))
except IndexError: # pop from empty list
return set()
其他回答
如果你将两个列表中较大的一个转换为一个集合,你可以使用intersection()获得该集合与任何可迭代对象的交集:
a = [1,2,3,4,5]
b = [1,3,5,6]
set(a).intersection(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}
你也可以使用numpy.intersect1d(ar1, ar2)。 它返回两个数组中唯一且已排序的值。
从较大的集合中创建一个集合:
_auxset = set(a)
然后,
c = [x for x in b if x in _auxset]
会做你想做的(保留b的顺序,而不是a的顺序——不一定能同时保留两者),而且动作要快。(使用a中的if x作为列表理解中的条件也可以工作,并且避免了构建_auxset的需要,但不幸的是,对于相当长的列表,它会慢得多)。
如果你想对结果进行排序,而不是保持列表的顺序,一个更整洁的方法可能是:
c = sorted(set(a).intersection(b))
这是一个示例,当您需要在结果中的每个元素出现的次数应该与它在两个数组中显示的次数相同。
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