如列表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)
如列表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)
本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。