Python从两个列表中取出相同和不同的元素

A = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]
B = [4, 5, 6, 7, 8, 9, 10, 9, 8, 11]
C = []  # 不同的元素
D = []  # 相同的元素
AB = A + B
for i in AB:
    if i in A and i in B:
        if i not in D:
            D.append(i)
        else:
            continue
    else:
        C.append(i)

print(D)
print(list(set(C)))  # 使用集合去重再转为列表

打印如下

[4, 5, 6, 7]
[1, 2, 3, 8, 9, 10, 11]

猜你喜欢

转载自blog.csdn.net/weixin_44801202/article/details/89086959