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操作(列表交集)?
当前回答
如果顺序不重要,你不需要担心重复,那么你可以使用set intersection:
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
其他回答
这样可以得到两个列表的交集,也可以得到公共重复项。
>>> 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]
这可能是晚了,但我只是认为我应该分享的情况下,你需要手动做(显示工作-哈哈)或当你需要所有元素出现尽可能多的次数或当你也需要它是唯一的。
请注意,还为它编写了测试。
from nose.tools import assert_equal
'''
Given two lists, print out the list of overlapping elements
'''
def overlap(l_a, l_b):
'''
compare the two lists l_a and l_b and return the overlapping
elements (intersecting) between the two
'''
#edge case is when they are the same lists
if l_a == l_b:
return [] #no overlapping elements
output = []
if len(l_a) == len(l_b):
for i in range(l_a): #same length so either one applies
if l_a[i] in l_b:
output.append(l_a[i])
#found all by now
#return output #if repetition does not matter
return list(set(output))
else:
#find the smallest and largest lists and go with that
sm = l_a if len(l_a) len(l_b) else l_b
for i in range(len(sm)):
if sm[i] in lg:
output.append(sm[i])
#return output #if repetition does not matter
return list(set(output))
## Test the Above Implementation
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
exp = [1, 2, 3, 5, 8, 13]
c = [4, 4, 5, 6]
d = [5, 7, 4, 8 ,6 ] #assuming it is not ordered
exp2 = [4, 5, 6]
class TestOverlap(object):
def test(self, sol):
t = sol(a, b)
assert_equal(t, exp)
print('Comparing the two lists produces')
print(t)
t = sol(c, d)
assert_equal(t, exp2)
print('Comparing the two lists produces')
print(t)
print('All Tests Passed!!')
t = TestOverlap()
t.test(overlap)
在这种情况下,你有一个列表的列表地图很方便:
>>> 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)
使用过滤器和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封装它返回输出列表。