Python的set对象表示内置set类。可以通过调用相应的方法或使用运算符来执行诸如并集,交集,差和对称差之类的不同集合操作。
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1.union(s2) {1, 2, 3, 4, 5, 6, 7, 8} >>> s2.union(s1) {1, 2, 3, 4, 5, 6, 7, 8}
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1|s2 {1, 2, 3, 4, 5, 6, 7, 8}
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1.intersection(s2) {4, 5} >>> s2.intersection(s1) {4, 5}
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1&s2 {4, 5} >>> s2&s1 {4, 5}
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1.difference(s2) {1, 2, 3} >>> s2.difference(s1) {8, 6, 7}
>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1-s2 {1, 2, 3} >>> s2-s1 {8, 6, 7}