349.兩個陣列的交集|python

sixkery發表於2018-10-07

列表推導式很強大。

def section(num1,num2):
    # 交集並集差集
    alist = [i for i in num1 if i in num2]
    alist2 = [i for i in num1 if i not in num2]
    alist3 = list(set(num1).union(set(num2)))

    print(alist,alist2,alist3)


if __name__ == `__main__`:
    num1 = [4,9,5]
    num2 = [9,4,9,8,4]
    section(num1,num2)

結果:
[4, 9] [5] [4, 5, 8, 9]


相關文章