交集、並集、差集
阿新 • • 發佈:2018-04-21
轉變 set pig dog 集合 style AS bee print
交集合
cat=[‘fish‘,‘beef‘,‘pig‘] dog=[‘beef‘,‘pig‘] #列表轉變為集合 cat1=set(cat) dog1=set(dog) print(cat1,dog1) 輸出{‘pig‘, ‘beef‘, ‘fish‘} {‘pig‘, ‘beef‘} print(cat1.intersection(dog1)) 輸出{‘pig‘, ‘beef‘} print(cat1&dog1) 輸出{‘pig‘, ‘beef‘}
並集
cat=[‘fish‘,‘beef‘,‘pig‘] dog=[‘beef‘,‘pig‘] #列表轉變為集合 cat1=set(cat) dog1=set(dog) print(cat1.union(dog1)) 輸出 {‘fish‘, ‘pig‘, ‘beef‘} print(cat1|dog1) 輸出{‘fish‘, ‘pig‘, ‘beef‘}
差集
cat=[‘fish‘,‘beef‘,‘pig‘] dog=[‘beef‘,‘pig‘] #列表轉變為集合 cat1=set(cat) dog1=set(dog) print(cat1-dog1) print(cat1.difference(dog1))
交集、並集、差集