python中给定两个列表,怎么找出他们相同的元素和不同的元素?

如列表a和列表b,则相同元素为1,不同元素为2,3,4,5,6

a = [1, 2, 3, 4]

b = [1, 5, 6]

1. 位运算
print(set(a) & set(b))

print(set(a) ^ set(b)) # 异或

2. 列表推导式
same = [x for x in a if x in b]

print(same)

diff = [y for y in (a + b) if y not in same]

print(diff)
posted @ 2020-04-09 18:36  newlangwen  阅读(1115)  评论(0编辑  收藏  举报