Python集合上的运算符和方法有什么区别?
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}