一、集合(set)

定义:由不同元素组成的集合,集合是一组无序排列的可hash值,可作为字典的key。

      ①:不同元素组成----》不重复

      ②:是无序的

      ③:集合中的元素必须是不可变类型(不能为list和dict)

特性:集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无须纠结集合中单个值。

1、集合的创建:

 定义可变集合:

     s=set('hello')

     print(s)  ------>{'h','e','o','l'}

 定义不可变集合:

     s=frozenset(set('hello'))

     这里面没有add pop remove...方法

2、集合常用操作:关系运算

   in

   not in 

   ==

   !=

   <,<=

   >,>=

   |,|= :并集

   &,&=:交集

   -,-=:差集

   ^,^=:交差补集

 

  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5     
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """
 10         Add an element to a set.
 11         
 12         This has no effect if the element is already present.
 13         """
 14         pass
 15 
 16     def clear(self, *args, **kwargs): # real signature unknown
 17         """ Remove all elements from this set. """
 18         pass
 19 
 20     def copy(self, *args, **kwargs): # real signature unknown
 21         """ Return a shallow copy of a set. """
 22         pass
 23 
 24     def difference(self, *args, **kwargs): # real signature unknown
 25         """
 26         相当于s1-s2
 27         
 28         Return the difference of two or more sets as a new set.
 29         
 30         (i.e. all elements that are in this set but not the others.)
 31         """
 32         pass
 33 
 34     def difference_update(self, *args, **kwargs): # real signature unknown
 35         """ Remove all elements of another set from this set. """
 36         pass
 37 
 38     def discard(self, *args, **kwargs): # real signature unknown
 39         """
 40         与remove功能相同,删除元素不存在时不会抛出异常
 41         
 42         Remove an element from a set if it is a member.
 43         
 44         If the element is not a member, do nothing.
 45         """
 46         pass
 47 
 48     def intersection(self, *args, **kwargs): # real signature unknown
 49         """
 50         相当于s1&s2
 51         
 52         Return the intersection of two sets as a new set.
 53         
 54         (i.e. all elements that are in both sets.)
 55         """
 56         pass
 57 
 58     def intersection_update(self, *args, **kwargs): # real signature unknown
 59         """ Update a set with the intersection of itself and another. """
 60         pass
 61 
 62     def isdisjoint(self, *args, **kwargs): # real signature unknown
 63         """ Return True if two sets have a null intersection. """
 64         pass
 65 
 66     def issubset(self, *args, **kwargs): # real signature unknown
 67         """ 
 68         相当于s1<=s2
 69         
 70         Report whether another set contains this set. """
 71         pass
 72 
 73     def issuperset(self, *args, **kwargs): # real signature unknown
 74         """
 75         相当于s1>=s2
 76         
 77          Report whether this set contains another set. """
 78         pass
 79 
 80     def pop(self, *args, **kwargs): # real signature unknown
 81         """
 82         Remove and return an arbitrary set element.
 83         Raises KeyError if the set is empty.
 84         """
 85         pass
 86 
 87     def remove(self, *args, **kwargs): # real signature unknown
 88         """
 89         Remove an element from a set; it must be a member.
 90         
 91         If the element is not a member, raise a KeyError.
 92         """
 93         pass
 94 
 95     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 96         """
 97         相当于s1^s2
 98         
 99         Return the symmetric difference of two sets as a new set.
100         
101         (i.e. all elements that are in exactly one of the sets.)
102         """
103         pass
104 
105     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
106         """ Update a set with the symmetric difference of itself and another. """
107         pass
108 
109     def union(self, *args, **kwargs): # real signature unknown
110         """
111         相当于s1|s2
112         
113         Return the union of sets as a new set.
114         
115         (i.e. all elements that are in either set.)
116         """
117         pass
118 
119     def update(self, *args, **kwargs): # real signature unknown
120         """ Update a set with the union of itself and others. """
121         pass
122 
123     def __and__(self, *args, **kwargs): # real signature unknown
124         """ Return self&value. """
125         pass
126 
127     def __contains__(self, y): # real signature unknown; restored from __doc__
128         """ x.__contains__(y) <==> y in x. """
129         pass
130 
131     def __eq__(self, *args, **kwargs): # real signature unknown
132         """ Return self==value. """
133         pass
134 
135     def __getattribute__(self, *args, **kwargs): # real signature unknown
136         """ Return getattr(self, name). """
137         pass
138 
139     def __ge__(self, *args, **kwargs): # real signature unknown
140         """ Return self>=value. """
141         pass
142 
143     def __gt__(self, *args, **kwargs): # real signature unknown
144         """ Return self>value. """
145         pass
146 
147     def __iand__(self, *args, **kwargs): # real signature unknown
148         """ Return self&=value. """
149         pass
150 
151     def __init__(self, seq=()): # known special case of set.__init__
152         """
153         set() -> new empty set object
154         set(iterable) -> new set object
155         
156         Build an unordered collection of unique elements.
157         # (copied from class doc)
158         """
159         pass
160 
161     def __ior__(self, *args, **kwargs): # real signature unknown
162         """ Return self|=value. """
163         pass
164 
165     def __isub__(self, *args, **kwargs): # real signature unknown
166         """ Return self-=value. """
167         pass
168 
169     def __iter__(self, *args, **kwargs): # real signature unknown
170         """ Implement iter(self). """
171         pass
172 
173     def __ixor__(self, *args, **kwargs): # real signature unknown
174         """ Return self^=value. """
175         pass
176 
177     def __len__(self, *args, **kwargs): # real signature unknown
178         """ Return len(self). """
179         pass
180 
181     def __le__(self, *args, **kwargs): # real signature unknown
182         """ Return self<=value. """
183         pass
184 
185     def __lt__(self, *args, **kwargs): # real signature unknown
186         """ Return self<value. """
187         pass
188 
189     @staticmethod # known case of __new__
190     def __new__(*args, **kwargs): # real signature unknown
191         """ Create and return a new object.  See help(type) for accurate signature. """
192         pass
193 
194     def __ne__(self, *args, **kwargs): # real signature unknown
195         """ Return self!=value. """
196         pass
197 
198     def __or__(self, *args, **kwargs): # real signature unknown
199         """ Return self|value. """
200         pass
201 
202     def __rand__(self, *args, **kwargs): # real signature unknown
203         """ Return value&self. """
204         pass
205 
206     def __reduce__(self, *args, **kwargs): # real signature unknown
207         """ Return state information for pickling. """
208         pass
209 
210     def __repr__(self, *args, **kwargs): # real signature unknown
211         """ Return repr(self). """
212         pass
213 
214     def __ror__(self, *args, **kwargs): # real signature unknown
215         """ Return value|self. """
216         pass
217 
218     def __rsub__(self, *args, **kwargs): # real signature unknown
219         """ Return value-self. """
220         pass
221 
222     def __rxor__(self, *args, **kwargs): # real signature unknown
223         """ Return value^self. """
224         pass
225 
226     def __sizeof__(self): # real signature unknown; restored from __doc__
227         """ S.__sizeof__() -> size of S in memory, in bytes """
228         pass
229 
230     def __sub__(self, *args, **kwargs): # real signature unknown
231         """ Return self-value. """
232         pass
233 
234     def __xor__(self, *args, **kwargs): # real signature unknown
235         """ Return self^value. """
236         pass
237 
238     __hash__ = None
239 
240 查看
241 
242 查看
查看

练习:

 1 # _*_ encoding:utf-8 _*_
 2 __author__ = 'listen'
 3 __date__ = '2018/11/10 11:28'
 4 #基本的方法:
 5 # s={1,2,3,4,5,'alex'}
 6 # # s.add('listen')  #{1, 2, 3, 4, 5, 'listen', 'alex'} #更新一个值
 7 # # s.pop() #{2, 3, 4, 5, 'alex'}随意删除一个元素
 8 # # s.remove(8) #集合中没有此元素,删除会报错
 9 # # s.remove(5)  #{1, 2, 3, 4, 'alex'} 删除指定元素
10 # # s.clear()  #set() 清空集合
11 # # s.discard(8) #删除指定元素,元素不存在,不会报错
12 # s.copy()  #{1, 2, 3, 4, 5, 'alex'}重新复制了一下
13 # print(s)
14 
15 
16 #交、差和并集
17 s1={1,2,3,4,'alex','student'}
18 s2={1,3,'alex','listen','worker'}
19 #交集
20 # v=s1.intersection(s2)
21 # s1.intersection_update(s2)
22 # print(s1)#s1被改变
23 # v1=s1&s2  #v1和v2一样
24 # print(v,v1)
25 
26 #差集
27 # v=s1.difference(s2)
28 # s1.difference_update(s2) #更新后返回s1
29 # print(s1)  #s1和v得到的结果是一样的
30 # # v1=s1-s2   #v和v1表示的一样
31 # print(v)
32 # # # print(v1)
33 
34 #并集
35 # v=s1.union(s2)
36 # s1.update(s2)#更新多个值 s1.update(('a','b','c))  s1.update(['1','b','c']) 只要为可迭代的就可以
37 # print(s1) #直接改变了s1{1, 2, 3, 4, 'alex', 'student', 'listen', 'worker'}
38 # v1=s1|s2
39 # print(v,v1)#v和v1效果一样{1, 2, 3, 4, 'alex', 'worker', 'student', 'listen'} {1, 2, 3, 4, 'alex', 'worker', 'student', 'listen'}
40 
41 #交差补集
42 # v=s1.symmetric_difference(s2) #自己所特有的
43 # s1.symmetric_difference_update(s2)
44 # print(s1)#更新s1的值
45 # v1=s1^s2
46 # print(v,v1)  #{2, 'worker', 4, 'listen', 'student'}  v和v1是一样的
47 
48 #子集、父集、交集为空
49 # s3={1,2}
50 # s4={3,4}
51 # print(s3.isdisjoint(s4)) #True 两个集合交集为空
52 
53 # s3={1,2}
54 # s4={1,2,3,4}
55 # print(s3.issubset(s4)) #True s3是s4的子集
56 # print(s4.issuperset(s3)) #True s4是s3的父集

 二、百分号方式

 

%[(name)][flags][width].[precision]typecode

    name    可选,用于选择指定的key

    flags   可选,可供选择的值有:

    • +       右对齐;正数前加正好,负数前加负号;
    • -        左对齐;正数前无符号,负数前加负号;
    • 空格    右对齐;正数前加空格,负数前加负号;
    • 0        右对齐;正数前无符号,负数前加负号;用0填充空白处
  • width       可选,占有宽度

  • .precision  可选,小数点后保留的位数

  • typecode    必选

    • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置

    • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置

    • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置

    • o,将整数转换成 八  进制表示,并将其格式化到指定位置

    • x,将整数转换成十六进制表示,并将其格式化到指定位置

    • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置

    • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)

    • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)

    • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)

    • F,同上

    • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)

    • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)

    • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

常用的格式化:

 

 1 # _*_ encoding:utf-8 _*_
 2 __author__ = 'listen'
 3 __date__ = '2018/11/10 13:50'
 4 tp1='I am %s' %'student'
 5 print(tp1)  #I am student
 6 
 7 tp2='I am %s age %d'%('alex',18)
 8 print(tp2)
 9 
10 tp3='I am %(name)s age %(age)d'%{'name':'alex','age':18}
11 print(tp3)
12 
13 tp4='percent %.2f'%23.2693 #取小数点后两位
14 print(tp4)
15 
16 tp5='my age is %(age).2f' %{'age':18.2356}
17 print(tp5)
18 
19 tp6='buy pen is my total money %.2f %%'%80.36
20 print(tp6)
21 
22 #结果:
23 # I am student
24 # I am alex age 18
25 # I am alex age 18
26 # percent 23.27
27 # my age is 18.24
28 # buy pen is my total money 80.36 %

 三、Format方式

 

[[fill]align][sign][#][width][,][.precision][type]
    • fill         【可选】空白处填充的字符

    • align        【可选】对齐方式(需配合width使用)

      • <,内容左对齐

      • >,内容右对齐(默认)

      • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字

      • ^,内容居中

    • sign      【可选】有无符号数字#            

      • +,正号加正,负号加负;

      •  -,正号不变,负号加负;

      • 空格 ,正号空格,负号加负;

    •   #            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示

    • ,         【可选】为数字添加分隔符,如:1,000,000

    • width      【可选】格式化位所占宽度

    • .precision  【可选】小数位保留精度

    • type        【可选】格式化类型

      •  传入” 字符串类型 “的参数

        • s,格式化字符串类型数据

        • 空白,未指定类型,则默认是None,同s

      • 传入“ 整数类型 ”的参数

 

b,将10进制整数自动转换成2进制表示然后格式化

 

 

c,将10进制整数自动转换为其对应的unicode字符

 

 

d,十进制整数

 

 

o,将10进制整数自动转换成8进制表示然后格式化;

 

 

x,将10进制整数自动转换成16进制表示然后格式化(小写x)

 

 

X,将10进制整数自动转换成16进制表示然后格式化(大写X)

 

      • 传入“ 浮点型或小数类型 ”的参数

        • e, 转换为科学计数法(小写e)表示,然后格式化;

        • E, 转换为科学计数法(大写E)表示,然后格式化;

        • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;

        • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;

        • g, 自动在e和f中切换

        • G, 自动在E和F中切换

        • %,显示百分比(默认显示小数点后6位)

 常用格式化:

 1 # _*_ encoding:utf-8 _*_
 2 __author__ = 'listen'
 3 __date__ = '2018/11/10 14:50'
 4 # tp1='I am {},age {}'.format('alex',18,'alex')
 5 # print(tp1) #I am alex,age 18 后面可以比前面多,前面比后面多报错
 6 
 7 # tp2='I am {},age {}'.format(*['alex',18,'alex'])
 8 # print(tp2) #列表得加一个*
 9 
10 # tp3='I am {0},age {1},really {0}'.format('alex',18)
11 # print(tp3)  #根据索引取,一个值可以使用多次
12 
13 # tp4='I am {0},age {1},really {0}'.format(*['alex',18])
14 # # print(tp4)
15 
16 # tp5='I am {name},age {age},really {name}'.format(name='alex',age=18)
17 # print(tp5)  #I am alex,age 18,really alex 字典形式
18 
19 # tp6='I am {name},age {age},really {name}'.format(**{'name':'alex','age':18})
20 # print(tp6)  #I am alex,age 18,really alex 用dict显示
21 
22 # tp7='I am {0[0]},age {0[1]} really {0[2]} '.format(['listen',15,15],[11,22,33])
23 # print(tp7) #I am listen,age 15 really 15  用list列表
24 
25 # tp8='I am {:s},age {:d},money {:f}'.format('steven',18,19.2587)
26 # print(tp8) #I am steven,age 18,money 19.258700  字符串  数字  浮点
27 
28 # tp9='I am {:s},age {:d},money {:f}'.format(*['steven',18,19.2587])
29 # print(tp9)  #I am steven,age 18,money 19.258700
30 
31 # tp10='I am {name:s},age {age:d}'.format(name='alex',age=18)
32 # print(tp10)  #I am alex,age 18
33 
34 # tp11='I am {name:s},age {age:d}'.format(**{'name':'alex','age':18})
35 # print(tp11)  #I am alex,age 18
36 
37 # tp12='numbers:{:b},{:o},{:d},{:x},{:X},{:%},{}'.format(15,15,15,15,15,15.87423,2)
38 # print(tp12)  #numbers:1111 二进制,17 八进制,15十进制,f 十六进制,F大写,1587.423000%, 默认小数点后面6位2
39 
40 # tp13='mumbers:{0:b},{0:o},{0:d},{0:x},{0:X},{0:%}'.format(15)
41 # print(tp13) #mumbers:1111,17,15,f,F,1500.000000%
42 
43 # tp14= "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
44 # print(tp14)  #numbers: 1111,17,15,f,F, 1500.000000%

 三、深拷贝和浅拷贝

浅拷贝:只拷贝元素的第一层(第一层相互独立、互不影响)    -----------若元素为可变类型(ep:list)一旦浅拷贝,两个都改变。

                                                                     若元素为不可变类型(ep;tuple、字符串、int),一个变,父亲不变。

   

 1 # li=[1,2,3,[4,5]]
 2 # a=li.copy()  #重新分配了一块地址
 3 # # a[1]=10
 4 # # print(li)  #[1, 2, 3, [4, 5]]  第一层拷贝 ==  第一层相互独立、互不影响
 5 # # print(a)  #[1, 10, 3, [4, 5]] #a修改a中的值不影响li的值
 6 #
 7 #
 8 # a[3][0]=6
 9 # print(li)  #[1, 2, 3, [6, 5]]  因为第四个元素是一个list,列表为可变类型,所以把原来的对象直接修改,而1,2,3,这些元素是int不可变类型,所以一旦修改重新创建一个新的内存,开辟一个新的空间,所以互不影响
10 # print(a)   #[1, 2, 3, [6, 5]]  整体作为一个地址,一旦改变就真的变了

 

深拷贝:先导入模块copy,再copy.deepcopy(),拷贝后成为完全独立的两个对象,复制相互独立、互不影响。

 1 #深拷贝
 2 import copy
 3 L=[1,2,3,4,5,[8,9]]
 4 b=copy.deepcopy(L)
 5 # b[5][0]=6
 6 # print(L)  #[1, 2, 3, 4, 5, [8, 9]]  即便可变类型改变值,最后也是互不影响
 7 # print(b)  #[1, 2, 3, 4, 5, [6, 9]]
 8 b[2]=12
 9 print(L)  #[1, 2, 3, 4, 5, [8, 9]]
10 print(b)    #[1, 2, 12, 4, 5, [8, 9]]