标签:style blog io ar color 使用 sp for strong
>>> set() #new empty set object set() >>> set([1,2,3,3,4]) #new set object {1, 2, 3, 4} >>> set("Hello World") {‘e‘, ‘H‘, ‘r‘, ‘ ‘, ‘d‘, ‘l‘, ‘o‘, ‘W‘}
>>> {1,2,3,3,4}
{1, 2, 3, 4}
set 的基本操作
>>> s = set([1,2,3,3]) >>> t = set([3,4,4,5]) >>> s|t # t 和 s的并集 {1, 2, 3, 4, 5} >>> s&t # t 和 s的交集 {3} >>> t-s # 求差集(项在t中,但不在s中) {4, 5} >>> t^s # 对称差集(项在t或s中,但不会同时出现在二者中) {1, 2, 4, 5}
>>> t = set([1,2,3,3]) # Add an element to a set #仅添加一项,添加list,或几项都会报错 >>> t.add(‘x‘) #添加一个字符 >>> t.add("Hello") #添加一个字符串 >>> t.add(8) #添加一个数值 >>> t {1, 2, 3, 8, ‘x‘, ‘Hello‘}
#Remove an element from a set; >>> t = set([1,2,3,‘H‘,‘E‘]) >>> t {1, 2, 3, ‘E‘, ‘H‘} >>> t.remove(3) >>> t {1, 2, ‘E‘, ‘H‘}
#t.remove(5)会报错
>>> t = set([1,2,2,3,‘H‘,‘E‘]) >>> t.discard(2) >>> t {1, 3, ‘E‘, ‘H‘} >>> t.discard(9) >>> t {1, 3, ‘E‘, ‘H‘}
#Update a set with the union of itself and others #可以实现添加多项,如list >>> t = set([1,2,3,3]) >>> t.update([3,4,5,5]) >>> t {1, 2, 3, 4, 5}
#Remove all elements from this set. >>> t = set([1,2,3,3]) >>> t.clear() >>> t set()
>>> s = {3,3,4,4} >>> c = s.copy() >>> c.add(5) >>> c {3, 4, 5} >>> s {3, 4}
>>> s = {3,3,4,4} >>> s {3, 4} >>> len(s) 2
>>> s = set([11,22,33,11,33,55]) >>> s {33, 11, 22, 55} >>> c = [i for i in s] >>> c [33, 11, 22, 55]
标签:style blog io ar color 使用 sp for strong
原文地址:http://www.cnblogs.com/qianwen/p/4112750.html