更新于 2020-03-02 10:21:19
402 阅读量
Python 的 set 对象表示内置的 set 类。可以通过调用相应的 method 或者使用 operator 来执行不同的 set 操作,例如 union、intersection、difference 和 symmetric difference。使用 method 的 Union>>> 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}使用 | operator 的 Union>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1|s2 {1, 2, 3, 4, 5, 6, 7, 8}使用 method 的 Intersection>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1.intersection(s2) {4, 5} >>> s2.intersection(s1) {4, 5}Intersection & operator>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1&s2 {4, 5} >>> s2&s1 {4, 5}Difference method>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1.difference(s2) {1, 2, 3} >>> s2.difference(s1) {8, 6, 7}Difference - operator>>> s1={1,2,3,4,5} >>> s2={4,5,6,7,8} >>> s1-s2 {1, 2, 3} >>> s2-s1 {8, 6, 7}