Python学习之路2☞数据类型与变量

变量

变量作用:保存状态:说白了,程序运行的状态就是状态的变化,变量是用来保存状态的,变量值的不断变化就产生了运行程序的最终输出结果

一:声明变量

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 name='sy'

上述代码声明了一个变量,变量名为: name,变量(name)的值为:"sy"

二:变量的定义规则

  • 变量名只能是 字母、数字或下划线的任意组合
  • 变量名的第一个字符不能是数字(是字母或下划线(_))
  • 大小写敏感
  • 两种风格:conn_obj或ConnObj
  • 不能使用关键字,不能使用内建

以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

三:变量赋值

链式赋值:y=x=z=1

多元赋值:x,y=1,2 x,y=y,x

增量/减量/乘量/除量 赋值:

变量解压赋值:

数据类型

数据类型是在数据结构中的定义是一个值的集合以及定义在这个值集上的一组操作。

一、数据类型分类:

1、数字

int(整型)

python2.*与python3.*关于整型的区别

python2.*
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
  1 class int(object):
  2     """
  3     int(x=0) -> int or long
  4     int(x, base=10) -> int or long
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is floating point, the conversion truncates towards zero.
  8     If x is outside the integer range, the function returns a long instead.
  9     
 10     If x is not a number or if base is given, then x must be a string or
 11     Unicode object representing an integer literal in the given base.  The
 12     literal can be preceded by '+' or '-' and be surrounded by whitespace.
 13     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 14     interpret the base from the string as an integer literal.
 15     >>> int('0b100', base=0)
 16     """
 17     def bit_length(self): 
 18         """ 返回表示该数字的时占用的最少位数 """
 19         """
 20         int.bit_length() -> int
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37)
 24         '0b100101'
 25         >>> (37).bit_length()
 26         """
 27         return 0
 28 
 29     def conjugate(self, *args, **kwargs): # real signature unknown
 30         """ 返回该复数的共轭复数 """
 31         """ Returns self, the complex conjugate of any int. """
 32         pass
 33 
 34     def __abs__(self):
 35         """ 返回绝对值 """
 36         """ x.__abs__() <==> abs(x) """
 37         pass
 38 
 39     def __add__(self, y):
 40         """ x.__add__(y) <==> x+y """
 41         pass
 42 
 43     def __and__(self, y):
 44         """ x.__and__(y) <==> x&y """
 45         pass
 46 
 47     def __cmp__(self, y): 
 48         """ 比较两个数大小 """
 49         """ x.__cmp__(y) <==> cmp(x,y) """
 50         pass
 51 
 52     def __coerce__(self, y):
 53         """ 强制生成一个元组 """ 
 54         """ x.__coerce__(y) <==> coerce(x, y) """
 55         pass
 56 
 57     def __divmod__(self, y): 
 58         """ 相除,得到商和余数组成的元组 """ 
 59         """ x.__divmod__(y) <==> divmod(x, y) """
 60         pass
 61 
 62     def __div__(self, y): 
 63         """ x.__div__(y) <==> x/y """
 64         pass
 65 
 66     def __float__(self): 
 67         """ 转换为浮点类型 """ 
 68         """ x.__float__() <==> float(x) """
 69         pass
 70 
 71     def __floordiv__(self, y): 
 72         """ x.__floordiv__(y) <==> x//y """
 73         pass
 74 
 75     def __format__(self, *args, **kwargs): # real signature unknown
 76         pass
 77 
 78     def __getattribute__(self, name): 
 79         """ x.__getattribute__('name') <==> x.name """
 80         pass
 81 
 82     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 83         """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
 84         pass
 85 
 86     def __hash__(self): 
 87         """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
 88         """ x.__hash__() <==> hash(x) """
 89         pass
 90 
 91     def __hex__(self): 
 92         """ 返回当前数的 十六进制 表示 """ 
 93         """ x.__hex__() <==> hex(x) """
 94         pass
 95 
 96     def __index__(self): 
 97         """ 用于切片,数字无意义 """
 98         """ x[y:z] <==> x[y.__index__():z.__index__()] """
 99         pass
100 
101     def __init__(self, x, base=10): # known special case of int.__init__
102         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
103         """
104         int(x=0) -> int or long
105         int(x, base=10) -> int or long
106         
107         Convert a number or string to an integer, or return 0 if no arguments
108         are given.  If x is floating point, the conversion truncates towards zero.
109         If x is outside the integer range, the function returns a long instead.
110         
111         If x is not a number or if base is given, then x must be a string or
112         Unicode object representing an integer literal in the given base.  The
113         literal can be preceded by '+' or '-' and be surrounded by whitespace.
114         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
115         interpret the base from the string as an integer literal.
116         >>> int('0b100', base=0)
117         # (copied from class doc)
118         """
119         pass
120 
121     def __int__(self): 
122         """ 转换为整数 """ 
123         """ x.__int__() <==> int(x) """
124         pass
125 
126     def __invert__(self): 
127         """ x.__invert__() <==> ~x """
128         pass
129 
130     def __long__(self): 
131         """ 转换为长整数 """ 
132         """ x.__long__() <==> long(x) """
133         pass
134 
135     def __lshift__(self, y): 
136         """ x.__lshift__(y) <==> x<<y """
137         pass
138 
139     def __mod__(self, y): 
140         """ x.__mod__(y) <==> x%y """
141         pass
142 
143     def __mul__(self, y): 
144         """ x.__mul__(y) <==> x*y """
145         pass
146 
147     def __neg__(self): 
148         """ x.__neg__() <==> -x """
149         pass
150 
151     @staticmethod # known case of __new__
152     def __new__(S, *more): 
153         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
154         pass
155 
156     def __nonzero__(self): 
157         """ x.__nonzero__() <==> x != 0 """
158         pass
159 
160     def __oct__(self): 
161         """ 返回改值的 八进制 表示 """ 
162         """ x.__oct__() <==> oct(x) """
163         pass
164 
165     def __or__(self, y): 
166         """ x.__or__(y) <==> x|y """
167         pass
168 
169     def __pos__(self): 
170         """ x.__pos__() <==> +x """
171         pass
172 
173     def __pow__(self, y, z=None): 
174         """ 幂,次方 """ 
175         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
176         pass
177 
178     def __radd__(self, y): 
179         """ x.__radd__(y) <==> y+x """
180         pass
181 
182     def __rand__(self, y): 
183         """ x.__rand__(y) <==> y&x """
184         pass
185 
186     def __rdivmod__(self, y): 
187         """ x.__rdivmod__(y) <==> divmod(y, x) """
188         pass
189 
190     def __rdiv__(self, y): 
191         """ x.__rdiv__(y) <==> y/x """
192         pass
193 
194     def __repr__(self): 
195         """转化为解释器可读取的形式 """
196         """ x.__repr__() <==> repr(x) """
197         pass
198 
199     def __str__(self): 
200         """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
201         """ x.__str__() <==> str(x) """
202         pass
203 
204     def __rfloordiv__(self, y): 
205         """ x.__rfloordiv__(y) <==> y//x """
206         pass
207 
208     def __rlshift__(self, y): 
209         """ x.__rlshift__(y) <==> y<<x """
210         pass
211 
212     def __rmod__(self, y): 
213         """ x.__rmod__(y) <==> y%x """
214         pass
215 
216     def __rmul__(self, y): 
217         """ x.__rmul__(y) <==> y*x """
218         pass
219 
220     def __ror__(self, y): 
221         """ x.__ror__(y) <==> y|x """
222         pass
223 
224     def __rpow__(self, x, z=None): 
225         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
226         pass
227 
228     def __rrshift__(self, y): 
229         """ x.__rrshift__(y) <==> y>>x """
230         pass
231 
232     def __rshift__(self, y): 
233         """ x.__rshift__(y) <==> x>>y """
234         pass
235 
236     def __rsub__(self, y): 
237         """ x.__rsub__(y) <==> y-x """
238         pass
239 
240     def __rtruediv__(self, y): 
241         """ x.__rtruediv__(y) <==> y/x """
242         pass
243 
244     def __rxor__(self, y): 
245         """ x.__rxor__(y) <==> y^x """
246         pass
247 
248     def __sub__(self, y): 
249         """ x.__sub__(y) <==> x-y """
250         pass
251 
252     def __truediv__(self, y): 
253         """ x.__truediv__(y) <==> x/y """
254         pass
255 
256     def __trunc__(self, *args, **kwargs): 
257         """ 返回数值被截取为整形的值,在整形中无意义 """
258         pass
259 
260     def __xor__(self, y): 
261         """ x.__xor__(y) <==> x^y """
262         pass
263 
264     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
265     """ 分母 = 1 """
266     """the denominator of a rational number in lowest terms"""
267 
268     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
269     """ 虚数,无意义 """
270     """the imaginary part of a complex number"""
271 
272     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
273     """ 分子 = 数字大小 """
274     """the numerator of a rational number in lowest terms"""
275 
276     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
277     """ 实属,无意义 """
278     """the real part of a complex number"""
279 
280 int
View Code
python3.*整形长度无限制
  1 class int(object):
  2     """
  3     int(x=0) -> integer
  4     int(x, base=10) -> integer
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is a number, return x.__int__().  For floating point
  8     numbers, this truncates towards zero.
  9     
 10     If x is not a number or if base is given, then x must be a string,
 11     bytes, or bytearray instance representing an integer literal in the
 12     given base.  The literal can be preceded by '+' or '-' and be surrounded
 13     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 14     Base 0 means to interpret the base from the string as an integer literal.
 15     >>> int('0b100', base=0)
 16     """
 17     def bit_length(self): # real signature unknown; restored from __doc__
 18         """ 返回表示该数字的时占用的最少位数 """
 19         """
 20         int.bit_length() -> int
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37)
 24         '0b100101'
 25         >>> (37).bit_length()
 26         """
 27         return 0
 28 
 29     def conjugate(self, *args, **kwargs): # real signature unknown
 30         """ 返回该复数的共轭复数 """
 31         """ Returns self, the complex conjugate of any int. """
 32         pass
 33 
 34     @classmethod # known case
 35     def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 36         """
 37         int.from_bytes(bytes, byteorder, *, signed=False) -> int
 38         
 39         Return the integer represented by the given array of bytes.
 40         
 41         The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
 42         
 43         The byteorder argument determines the byte order used to represent the
 44         integer.  If byteorder is 'big', the most significant byte is at the
 45         beginning of the byte array.  If byteorder is 'little', the most
 46         significant byte is at the end of the byte array.  To request the native
 47         byte order of the host system, use `sys.byteorder' as the byte order value.
 48         
 49         The signed keyword-only argument indicates whether two's complement is
 50         used to represent the integer.
 51         """
 52         pass
 53 
 54     def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 55         """
 56         int.to_bytes(length, byteorder, *, signed=False) -> bytes
 57         
 58         Return an array of bytes representing an integer.
 59         
 60         The integer is represented using length bytes.  An OverflowError is
 61         raised if the integer is not representable with the given number of
 62         bytes.
 63         
 64         The byteorder argument determines the byte order used to represent the
 65         integer.  If byteorder is 'big', the most significant byte is at the
 66         beginning of the byte array.  If byteorder is 'little', the most
 67         significant byte is at the end of the byte array.  To request the native
 68         byte order of the host system, use `sys.byteorder' as the byte order value.
 69         
 70         The signed keyword-only argument determines whether two's complement is
 71         used to represent the integer.  If signed is False and a negative integer
 72         is given, an OverflowError is raised.
 73         """
 74         pass
 75 
 76     def __abs__(self, *args, **kwargs): # real signature unknown
 77         """ abs(self) """
 78         pass
 79 
 80     def __add__(self, *args, **kwargs): # real signature unknown
 81         """ Return self+value. """
 82         pass
 83 
 84     def __and__(self, *args, **kwargs): # real signature unknown
 85         """ Return self&value. """
 86         pass
 87 
 88     def __bool__(self, *args, **kwargs): # real signature unknown
 89         """ self != 0 """
 90         pass
 91 
 92     def __ceil__(self, *args, **kwargs): # real signature unknown
 93         """
 94         整数返回自己
 95         如果是小数
 96          math.ceil(3.1)返回4
 97         """
 98         """ Ceiling of an Integral returns itself. """
 99         pass
100 
101     def __divmod__(self, *args, **kwargs): # real signature unknown
102         """ 相除,得到商和余数组成的元组 """
103         """ Return divmod(self, value). """
104         pass
105 
106     def __eq__(self, *args, **kwargs): # real signature unknown
107         """ Return self==value. """
108         pass
109 
110     def __float__(self, *args, **kwargs): # real signature unknown
111         """ float(self) """
112         pass
113 
114     def __floordiv__(self, *args, **kwargs): # real signature unknown
115         """ Return self//value. """
116         pass
117 
118     def __floor__(self, *args, **kwargs): # real signature unknown
119         """ Flooring an Integral returns itself. """
120         pass
121 
122     def __format__(self, *args, **kwargs): # real signature unknown
123         pass
124 
125     def __getattribute__(self, *args, **kwargs): # real signature unknown
126         """ Return getattr(self, name). """
127         pass
128 
129     def __getnewargs__(self, *args, **kwargs): # real signature unknown
130         pass
131 
132     def __ge__(self, *args, **kwargs): # real signature unknown
133         """ Return self>=value. """
134         pass
135 
136     def __gt__(self, *args, **kwargs): # real signature unknown
137         """ Return self>value. """
138         pass
139 
140     def __hash__(self, *args, **kwargs): # real signature unknown
141         """ Return hash(self). """
142         pass
143 
144     def __index__(self, *args, **kwargs): # real signature unknown
145         """ 用于切片,数字无意义 """
146         """ Return self converted to an integer, if self is suitable for use as an index into a list. """
147         pass
148 
149     def __init__(self, x, base=10): # known special case of int.__init__
150         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
151         """
152         int(x=0) -> integer
153         int(x, base=10) -> integer
154         
155         Convert a number or string to an integer, or return 0 if no arguments
156         are given.  If x is a number, return x.__int__().  For floating point
157         numbers, this truncates towards zero.
158         
159         If x is not a number or if base is given, then x must be a string,
160         bytes, or bytearray instance representing an integer literal in the
161         given base.  The literal can be preceded by '+' or '-' and be surrounded
162         by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
163         Base 0 means to interpret the base from the string as an integer literal.
164         >>> int('0b100', base=0)
165         # (copied from class doc)
166         """
167         pass
168 
169     def __int__(self, *args, **kwargs): # real signature unknown
170 
171         """ int(self) """
172         pass
173 
174     def __invert__(self, *args, **kwargs): # real signature unknown
175         """ ~self """
176         pass
177 
178     def __le__(self, *args, **kwargs): # real signature unknown
179         """ Return self<=value. """
180         pass
181 
182     def __lshift__(self, *args, **kwargs): # real signature unknown
183         """ Return self<<value. """
184         pass
185 
186     def __lt__(self, *args, **kwargs): # real signature unknown
187         """ Return self<value. """
188         pass
189 
190     def __mod__(self, *args, **kwargs): # real signature unknown
191         """ Return self%value. """
192         pass
193 
194     def __mul__(self, *args, **kwargs): # real signature unknown
195         """ Return self*value. """
196         pass
197 
198     def __neg__(self, *args, **kwargs): # real signature unknown
199         """ -self """
200         pass
201 
202     @staticmethod # known case of __new__
203     def __new__(*args, **kwargs): # real signature unknown
204         """ Create and return a new object.  See help(type) for accurate signature. """
205         pass
206 
207     def __ne__(self, *args, **kwargs): # real signature unknown
208         """ Return self!=value. """
209         pass
210 
211     def __or__(self, *args, **kwargs): # real signature unknown
212         """ Return self|value. """
213         pass
214 
215     def __pos__(self, *args, **kwargs): # real signature unknown
216         """ +self """
217         pass
218 
219     def __pow__(self, *args, **kwargs): # real signature unknown
220         """ Return pow(self, value, mod). """
221         pass
222 
223     def __radd__(self, *args, **kwargs): # real signature unknown
224         """ Return value+self. """
225         pass
226 
227     def __rand__(self, *args, **kwargs): # real signature unknown
228         """ Return value&self. """
229         pass
230 
231     def __rdivmod__(self, *args, **kwargs): # real signature unknown
232         """ Return divmod(value, self). """
233         pass
234 
235     def __repr__(self, *args, **kwargs): # real signature unknown
236         """ Return repr(self). """
237         pass
238 
239     def __rfloordiv__(self, *args, **kwargs): # real signature unknown
240         """ Return value//self. """
241         pass
242 
243     def __rlshift__(self, *args, **kwargs): # real signature unknown
244         """ Return value<<self. """
245         pass
246 
247     def __rmod__(self, *args, **kwargs): # real signature unknown
248         """ Return value%self. """
249         pass
250 
251     def __rmul__(self, *args, **kwargs): # real signature unknown
252         """ Return value*self. """
253         pass
254 
255     def __ror__(self, *args, **kwargs): # real signature unknown
256         """ Return value|self. """
257         pass
258 
259     def __round__(self, *args, **kwargs): # real signature unknown
260         """
261         Rounding an Integral returns itself.
262         Rounding with an ndigits argument also returns an integer.
263         """
264         pass
265 
266     def __rpow__(self, *args, **kwargs): # real signature unknown
267         """ Return pow(value, self, mod). """
268         pass
269 
270     def __rrshift__(self, *args, **kwargs): # real signature unknown
271         """ Return value>>self. """
272         pass
273 
274     def __rshift__(self, *args, **kwargs): # real signature unknown
275         """ Return self>>value. """
276         pass
277 
278     def __rsub__(self, *args, **kwargs): # real signature unknown
279         """ Return value-self. """
280         pass
281 
282     def __rtruediv__(self, *args, **kwargs): # real signature unknown
283         """ Return value/self. """
284         pass
285 
286     def __rxor__(self, *args, **kwargs): # real signature unknown
287         """ Return value^self. """
288         pass
289 
290     def __sizeof__(self, *args, **kwargs): # real signature unknown
291         """ Returns size in memory, in bytes """
292         pass
293 
294     def __str__(self, *args, **kwargs): # real signature unknown
295         """ Return str(self). """
296         pass
297 
298     def __sub__(self, *args, **kwargs): # real signature unknown
299         """ Return self-value. """
300         pass
301 
302     def __truediv__(self, *args, **kwargs): # real signature unknown
303         """ Return self/value. """
304         pass
305 
306     def __trunc__(self, *args, **kwargs): # real signature unknown
307         """ Truncating an Integral returns itself. """
308         pass
309 
310     def __xor__(self, *args, **kwargs): # real signature unknown
311         """ Return self^value. """
312         pass
313 
314     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
315     """the denominator of a rational number in lowest terms"""
316 
317     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
318     """the imaginary part of a complex number"""
319 
320     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
321     """the numerator of a rational number in lowest terms"""
322 
323     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
324     """the real part of a complex number"""
325 
326 python3.5
View Code

long(长整型)

 python2.*:
跟C语言不同,Python的长整型没有指定位宽,也就是说Python没有限制长整型数值的大小,
但是实际上由于机器内存有限,所以我们使用的长整型数值不可能无限大。
在使用过程中,我们如何区分长整型和整型数值呢?
通常的做法是在数字尾部加上一个大写字母L或小写字母l以表示该整数是长整型的,例如:
a = 9223372036854775808L
注意,自从Python2起,如果发生溢出,Python会自动将整型数据转换为长整型,
所以如今在长整型数据后面不加字母L也不会导致严重后果了。

python3.*
长整型,整型统一归为整型
   eg:
  

float(浮点型)

   浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x109和12.3x108是完全相等的。浮点数可以用数学写法,如1.233.14-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23x109就是1.23e9,或者12.3e8,0.000012可以写成1.2e-5,等等。

    整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差

2、布尔值

  真(True)或假(False)
  0和空,None都是False,其他的全部为True

3:浮点数

浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x109和12.3x108是完全相等的。浮点数可以用数学写法,如1.233.14-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23x109就是1.23e9,或者12.3e8,0.000012可以写成1.2e-5,等等。

整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差

4:复数

复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。(虚数部分的字母j大小写都可以)

1 >>> 1.3 + 2.5j == 1.3 + 2.5J
2 True

5:与数字有关的内置函数 

二:字符串

定义:

它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串

特性:

只能存放一个值

不可变

按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

1:字符串创建

a='hello word'

注:单引号和双引号没有任何区别

2:字符串的常用方法

 1 name="yyp"
 2 print(name.capitalize())#首字母变成大写
 3 print(name.center(30)) # 居中
 4 print(name.center(30,'*'))#居中加填充
 5  
 6 msg='hello world'
 7 print(msg.count('l'))#统计出现l在msg中出现的次数
 8 print(msg.count('l',0,3))#统计l在msg中0到3之间l出现的次数
 9 print(msg.count('l',-1))#统计l在msg中最后一个字符中出现l的次数
10 print(msg.endswith('s'))#判断msg是不是以s结尾,不是则为False,是为True
11 print(msg.startswith('h'))#判断msg是不是以h开头,不是则为False,是为True
12 print(msg.find('l'))#统计l出现的位置,如果不存在,则返回-1,存在返回位置,存在多个,只返回第一个出现的位置
13 print(msg.find('l',3,9))#统计l在msg的3到9之间,l出现的位置
14 print(msg.index('e'))#index与find本质区别是:index已经知道msg中存在e,然后进行查找,如果不存在会报错。
15 print(msg.isdigit())#判断字符串中是否包含数字,包含数字为False,不包含为True
16  
17 msg='hello world'#多用于字符串拼接
18 msg_new='*'.join(msg)
19 print(msg_new)
20  
21 msg='root:x:0:0:root:/bin/bash'
22 print(msg.split(':')) #split分割
23 print(msg.split(':',maxsplit=1))#以:为分割符,最大分割一次
24  
25 msg_list=msg.split(':')
26 print(':'.join(msg_list))#按照:拼接字符串
27  
28 msg='helLo world'
29 print(msg.upper())#小写转化为大写
30 print(msg.swapcase())#大小写转换
31  
32 msg='*****yyp*****'
33 print(msg.strip('*'))#去掉首尾的指定字符
34 print(msg.lstrip('*'))#去除左边指定字符
35 print(msg.rstrip('*'))#去除右边指定字符
36  
37  
38 print(msg.replace('z','y')) #替换字符,不指定个数全部替换,指定几个就替换几个
39 print(msg.replace('y','p',1))
View Code

3:字符串不常用的方法

 1 #不常用的方法
 2 msg='hello world'
 3 print(msg.isalpha())#msg是纯字母返回True,不是则返回False
 4 print(msg.isidentifier())#msg是内置标识符,返回True,否则返回False
 5 print(msg.isspace())#msg是空格,返回True,反之,返回False
 6 print(msg.istitle())#msg是标题,也就是首字母大写,返回True
 7 print(msg.ljust(10))#10个字符左对齐
 8 print(msg.ljust(10,'*'))#10个字符左对齐,10个字符*填充
 9 print(msg.rjust(10))#10个字符右对齐
10 print(msg.rjust(10,'*'))#10个字符右对齐,10个字符*填充
11 print(msg.zfill(20))#总长度20个,不足则在右边添加0
12  
13 message='''aaa
14 bbb
15 ccc
16 ddd
17 '''
18 print(message.splitlines()) #按照行数切分
View Code

4:字符串工厂函数

  1 class str(object):
  2     """
  3     str(object='') -> str
  4     str(bytes_or_buffer[, encoding[, errors]]) -> str
  5  
  6     Create a new string object from the given object. If encoding or
  7     errors is specified, then the object must expose a data buffer
  8     that will be decoded using the given encoding and error handler.
  9     Otherwise, returns the result of object.__str__() (if defined)
 10     or repr(object).
 11     encoding defaults to sys.getdefaultencoding().
 12     errors defaults to 'strict'.
 13     """
 14     def capitalize(self): # real signature unknown; restored from __doc__
 15         """
 16         首字母变大写
 17         S.capitalize() -> str
 18  
 19         Return a capitalized version of S, i.e. make the first character
 20         have upper case and the rest lower case.
 21         """
 22         return ""
 23  
 24     def casefold(self): # real signature unknown; restored from __doc__
 25         """
 26         S.casefold() -> str
 27  
 28         Return a version of S suitable for caseless comparisons.
 29         """
 30         return ""
 31  
 32     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 33         """
 34         原来字符居中,不够用空格补全
 35         S.center(width[, fillchar]) -> str
 36  
 37         Return S centered in a string of length width. Padding is
 38         done using the specified fill character (default is a space)
 39         """
 40         return ""
 41  
 42     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 43         """
 44          从一个范围内的统计某str出现次数
 45         S.count(sub[, start[, end]]) -> int
 46  
 47         Return the number of non-overlapping occurrences of substring sub in
 48         string S[start:end].  Optional arguments start and end are
 49         interpreted as in slice notation.
 50         """
 51         return 0
 52  
 53     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 54         """
 55         encode(encoding='utf-8',errors='strict')
 56         以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是
 57         ignore或replace
 58  
 59         S.encode(encoding='utf-8', errors='strict') -> bytes
 60  
 61         Encode S using the codec registered for encoding. Default encoding
 62         is 'utf-8'. errors may be given to set a different error
 63         handling scheme. Default is 'strict' meaning that encoding errors raise
 64         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 65         'xmlcharrefreplace' as well as any other name registered with
 66         codecs.register_error that can handle UnicodeEncodeErrors.
 67         """
 68         return b""
 69  
 70     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 71         """
 72         S.endswith(suffix[, start[, end]]) -> bool
 73  
 74         Return True if S ends with the specified suffix, False otherwise.
 75         With optional start, test S beginning at that position.
 76         With optional end, stop comparing S at that position.
 77         suffix can also be a tuple of strings to try.
 78         """
 79         return False
 80  
 81     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 82         """
 83         将字符串中包含的	转换成tabsize个空格
 84         S.expandtabs(tabsize=8) -> str
 85  
 86         Return a copy of S where all tab characters are expanded using spaces.
 87         If tabsize is not given, a tab size of 8 characters is assumed.
 88         """
 89         return ""
 90  
 91     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 92         """
 93         S.find(sub[, start[, end]]) -> int
 94  
 95         Return the lowest index in S where substring sub is found,
 96         such that sub is contained within S[start:end].  Optional
 97         arguments start and end are interpreted as in slice notation.
 98  
 99         Return -1 on failure.
100         """
101         return 0
102  
103     def format(self, *args, **kwargs): # known special case of str.format
104         """
105         格式化输出
106         三种形式:
107         形式一.
108         >>> print('{0}{1}{0}'.format('a','b'))
109         aba
110  
111         形式二:(必须一一对应)
112         >>> print('{}{}{}'.format('a','b'))
113         Traceback (most recent call last):
114           File "<input>", line 1, in <module>
115         IndexError: tuple index out of range
116         >>> print('{}{}'.format('a','b'))
117         ab
118  
119         形式三:
120         >>> print('{name} {age}'.format(age=12,name='lhf'))
121         lhf 12
122  
123         S.format(*args, **kwargs) -> str
124  
125         Return a formatted version of S, using substitutions from args and kwargs.
126         The substitutions are identified by braces ('{' and '}').
127         """
128         pass
129  
130     def format_map(self, mapping): # real signature unknown; restored from __doc__
131         """
132         与format区别
133         '{name}'.format(**dict(name='alex'))
134         '{name}'.format_map(dict(name='alex'))
135  
136         S.format_map(mapping) -> str
137  
138         Return a formatted version of S, using substitutions from mapping.
139         The substitutions are identified by braces ('{' and '}').
140         """
141         return ""
142  
143     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
144         """
145         S.index(sub[, start[, end]]) -> int
146  
147         Like S.find() but raise ValueError when the substring is not found.
148         """
149         return 0
150  
151     def isalnum(self): # real signature unknown; restored from __doc__
152         """
153         至少一个字符,且都是字母或数字才返回True
154  
155         S.isalnum() -> bool
156  
157         Return True if all characters in S are alphanumeric
158         and there is at least one character in S, False otherwise.
159         """
160         return False
161  
162     def isalpha(self): # real signature unknown; restored from __doc__
163         """
164         至少一个字符,且都是字母才返回True
165         S.isalpha() -> bool
166  
167         Return True if all characters in S are alphabetic
168         and there is at least one character in S, False otherwise.
169         """
170         return False
171  
172     def isdecimal(self): # real signature unknown; restored from __doc__
173         """
174         S.isdecimal() -> bool
175  
176         Return True if there are only decimal characters in S,
177         False otherwise.
178         """
179         return False
180  
181     def isdigit(self): # real signature unknown; restored from __doc__
182         """
183         S.isdigit() -> bool
184  
185         Return True if all characters in S are digits
186         and there is at least one character in S, False otherwise.
187         """
188         return False
189  
190     def isidentifier(self): # real signature unknown; restored from __doc__
191         """
192         字符串为关键字返回True
193  
194         S.isidentifier() -> bool
195  
196         Return True if S is a valid identifier according
197         to the language definition.
198  
199         Use keyword.iskeyword() to test for reserved identifiers
200         such as "def" and "class".
201         """
202         return False
203  
204     def islower(self): # real signature unknown; restored from __doc__
205         """
206         至少一个字符,且都是小写字母才返回True
207         S.islower() -> bool
208  
209         Return True if all cased characters in S are lowercase and there is
210         at least one cased character in S, False otherwise.
211         """
212         return False
213  
214     def isnumeric(self): # real signature unknown; restored from __doc__
215         """
216         S.isnumeric() -> bool
217  
218         Return True if there are only numeric characters in S,
219         False otherwise.
220         """
221         return False
222  
223     def isprintable(self): # real signature unknown; restored from __doc__
224         """
225         S.isprintable() -> bool
226  
227         Return True if all characters in S are considered
228         printable in repr() or S is empty, False otherwise.
229         """
230         return False
231  
232     def isspace(self): # real signature unknown; restored from __doc__
233         """
234         至少一个字符,且都是空格才返回True
235         S.isspace() -> bool
236  
237         Return True if all characters in S are whitespace
238         and there is at least one character in S, False otherwise.
239         """
240         return False
241  
242     def istitle(self): # real signature unknown; restored from __doc__
243         """
244         >>> a='Hello'
245         >>> a.istitle()
246         True
247         >>> a='HellP'
248         >>> a.istitle()
249         False
250  
251         S.istitle() -> bool
252  
253         Return True if S is a titlecased string and there is at least one
254         character in S, i.e. upper- and titlecase characters may only
255         follow uncased characters and lowercase characters only cased ones.
256         Return False otherwise.
257         """
258         return False
259  
260     def isupper(self): # real signature unknown; restored from __doc__
261         """
262         S.isupper() -> bool
263  
264         Return True if all cased characters in S are uppercase and there is
265         at least one cased character in S, False otherwise.
266         """
267         return False
268  
269     def join(self, iterable): # real signature unknown; restored from __doc__
270         """
271         #对序列进行操作(分别使用' '与':'作为分隔符)
272         >>> seq1 = ['hello','good','boy','doiido']
273         >>> print ' '.join(seq1)
274         hello good boy doiido
275         >>> print ':'.join(seq1)
276         hello:good:boy:doiido
277  
278  
279         #对字符串进行操作
280  
281         >>> seq2 = "hello good boy doiido"
282         >>> print ':'.join(seq2)
283         h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
284  
285  
286         #对元组进行操作
287  
288         >>> seq3 = ('hello','good','boy','doiido')
289         >>> print ':'.join(seq3)
290         hello:good:boy:doiido
291  
292  
293         #对字典进行操作
294  
295         >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
296         >>> print ':'.join(seq4)
297         boy:good:doiido:hello
298  
299  
300         #合并目录
301  
302         >>> import os
303         >>> os.path.join('/hello/','good/boy/','doiido')
304         '/hello/good/boy/doiido'
305  
306  
307         S.join(iterable) -> str
308  
309         Return a string which is the concatenation of the strings in the
310         iterable.  The separator between elements is S.
311         """
312         return ""
313  
314     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
315         """
316         S.ljust(width[, fillchar]) -> str
317  
318         Return S left-justified in a Unicode string of length width. Padding is
319         done using the specified fill character (default is a space).
320         """
321         return ""
322  
323     def lower(self): # real signature unknown; restored from __doc__
324         """
325         S.lower() -> str
326  
327         Return a copy of the string S converted to lowercase.
328         """
329         return ""
330  
331     def lstrip(self, chars=None): # real signature unknown; restored from __doc__
332         """
333         S.lstrip([chars]) -> str
334  
335         Return a copy of the string S with leading whitespace removed.
336         If chars is given and not None, remove characters in chars instead.
337         """
338         return ""
339  
340     def maketrans(self, *args, **kwargs): # real signature unknown
341         """
342         Return a translation table usable for str.translate().
343  
344         If there is only one argument, it must be a dictionary mapping Unicode
345         ordinals (integers) or characters to Unicode ordinals, strings or None.
346         Character keys will be then converted to ordinals.
347         If there are two arguments, they must be strings of equal length, and
348         in the resulting dictionary, each character in x will be mapped to the
349         character at the same position in y. If there is a third argument, it
350         must be a string, whose characters will be mapped to None in the result.
351         """
352         pass
353  
354     def partition(self, sep): # real signature unknown; restored from __doc__
355         """
356         以sep为分割,将S分成head,sep,tail三部分
357  
358         S.partition(sep) -> (head, sep, tail)
359  
360         Search for the separator sep in S, and return the part before it,
361         the separator itself, and the part after it.  If the separator is not
362         found, return S and two empty strings.
363         """
364         pass
365  
366     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
367         """
368         S.replace(old, new[, count]) -> str
369  
370         Return a copy of S with all occurrences of substring
371         old replaced by new.  If the optional argument count is
372         given, only the first count occurrences are replaced.
373         """
374         return ""
375  
376     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
377         """
378         S.rfind(sub[, start[, end]]) -> int
379  
380         Return the highest index in S where substring sub is found,
381         such that sub is contained within S[start:end].  Optional
382         arguments start and end are interpreted as in slice notation.
383  
384         Return -1 on failure.
385         """
386         return 0
387  
388     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
389         """
390         S.rindex(sub[, start[, end]]) -> int
391  
392         Like S.rfind() but raise ValueError when the substring is not found.
393         """
394         return 0
395  
396     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
397         """
398         S.rjust(width[, fillchar]) -> str
399  
400         Return S right-justified in a string of length width. Padding is
401         done using the specified fill character (default is a space).
402         """
403         return ""
404  
405     def rpartition(self, sep): # real signature unknown; restored from __doc__
406         """
407         S.rpartition(sep) -> (head, sep, tail)
408  
409         Search for the separator sep in S, starting at the end of S, and return
410         the part before it, the separator itself, and the part after it.  If the
411         separator is not found, return two empty strings and S.
412         """
413         pass
414  
415     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
416         """
417         S.rsplit(sep=None, maxsplit=-1) -> list of strings
418  
419         Return a list of the words in S, using sep as the
420         delimiter string, starting at the end of the string and
421         working to the front.  If maxsplit is given, at most maxsplit
422         splits are done. If sep is not specified, any whitespace string
423         is a separator.
424         """
425         return []
426  
427     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
428         """
429         S.rstrip([chars]) -> str
430  
431         Return a copy of the string S with trailing whitespace removed.
432         If chars is given and not None, remove characters in chars instead.
433         """
434         return ""
435  
436     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
437         """
438         以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,
439         如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
440         >>> a='a,b c
d	e'
441         >>> a.split()
442         ['a,b', 'c', 'd', 'e']
443         S.split(sep=None, maxsplit=-1) -> list of strings
444  
445         Return a list of the words in S, using sep as the
446         delimiter string.  If maxsplit is given, at most maxsplit
447         splits are done. If sep is not specified or is None, any
448         whitespace string is a separator and empty strings are
449         removed from the result.
450         """
451         return []
452  
453     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
454         """
455         Python splitlines() 按照行('
', '
', 
')分隔,
456         返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如        果为 True,则保留换行符。
457         >>> x
458         'adsfasdf
sadf
asdf
adf'
459         >>> x.splitlines()
460         ['adsfasdf', 'sadf', 'asdf', 'adf']
461         >>> x.splitlines(True)
462         ['adsfasdf
', 'sadf
', 'asdf
', 'adf']
463  
464         S.splitlines([keepends]) -> list of strings
465  
466         Return a list of the lines in S, breaking at line boundaries.
467         Line breaks are not included in the resulting list unless keepends
468         is given and true.
469         """
470         return []
471  
472     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
473         """
474         S.startswith(prefix[, start[, end]]) -> bool
475  
476         Return True if S starts with the specified prefix, False otherwise.
477         With optional start, test S beginning at that position.
478         With optional end, stop comparing S at that position.
479         prefix can also be a tuple of strings to try.
480         """
481         return False
482  
483     def strip(self, chars=None): # real signature unknown; restored from __doc__
484         """
485         S.strip([chars]) -> str
486  
487         Return a copy of the string S with leading and trailing
488         whitespace removed.
489         If chars is given and not None, remove characters in chars instead.
490         """
491         return ""
492  
493     def swapcase(self): # real signature unknown; restored from __doc__
494         """
495         大小写反转
496         S.swapcase() -> str
497  
498         Return a copy of S with uppercase characters converted to lowercase
499         and vice versa.
500         """
501         return ""
502  
503     def title(self): # real signature unknown; restored from __doc__
504         """
505         S.title() -> str
506  
507         Return a titlecased version of S, i.e. words start with title case
508         characters, all remaining cased characters have lower case.
509         """
510         return ""
511  
512     def translate(self, table): # real signature unknown; restored from __doc__
513         """
514         table=str.maketrans('alex','big SB')
515  
516         a='hello abc'
517         print(a.translate(table))
518  
519         S.translate(table) -> str
520  
521         Return a copy of the string S in which each character has been mapped
522         through the given translation table. The table must implement
523         lookup/indexing via __getitem__, for instance a dictionary or list,
524         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
525         this operation raises LookupError, the character is left untouched.
526         Characters mapped to None are deleted.
527         """
528         return ""
529  
530     def upper(self): # real signature unknown; restored from __doc__
531         """
532         S.upper() -> str
533  
534         Return a copy of S converted to uppercase.
535         """
536         return ""
537  
538     def zfill(self, width): # real signature unknown; restored from __doc__
539         """
540         原来字符右对齐,不够用0补齐
541          
542         S.zfill(width) -> str
543  
544         Pad a numeric string S with zeros on the left, to fill a field
545         of the specified width. The string S is never truncated.
546         """
547         return ""
548  
549     def __add__(self, *args, **kwargs): # real signature unknown
550         """ Return self+value. """
551         pass
552  
553     def __contains__(self, *args, **kwargs): # real signature unknown
554         """ Return key in self. """
555         pass
556  
557     def __eq__(self, *args, **kwargs): # real signature unknown
558         """ Return self==value. """
559         pass
560  
561     def __format__(self, format_spec): # real signature unknown; restored from __doc__
562         """
563         S.__format__(format_spec) -> str
564  
565         Return a formatted version of S as described by format_spec.
566         """
567         return ""
568  
569     def __getattribute__(self, *args, **kwargs): # real signature unknown
570         """ Return getattr(self, name). """
571         pass
572  
573     def __getitem__(self, *args, **kwargs): # real signature unknown
574         """ Return self[key]. """
575         pass
576  
577     def __getnewargs__(self, *args, **kwargs): # real signature unknown
578         pass
579  
580     def __ge__(self, *args, **kwargs): # real signature unknown
581         """ Return self>=value. """
582         pass
583  
584     def __gt__(self, *args, **kwargs): # real signature unknown
585         """ Return self>value. """
586         pass
587  
588     def __hash__(self, *args, **kwargs): # real signature unknown
589         """ Return hash(self). """
590         pass
591  
592     def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
593         """
594         str(object='') -> str
595         str(bytes_or_buffer[, encoding[, errors]]) -> str
596  
597         Create a new string object from the given object. If encoding or
598         errors is specified, then the object must expose a data buffer
599         that will be decoded using the given encoding and error handler.
600         Otherwise, returns the result of object.__str__() (if defined)
601         or repr(object).
602         encoding defaults to sys.getdefaultencoding().
603         errors defaults to 'strict'.
604         # (copied from class doc)
605         """
606         pass
607  
608     def __iter__(self, *args, **kwargs): # real signature unknown
609         """ Implement iter(self). """
610         pass
611  
612     def __len__(self, *args, **kwargs): # real signature unknown
613         """ Return len(self). """
614         pass
615  
616     def __le__(self, *args, **kwargs): # real signature unknown
617         """ Return self<=value. """
618         pass
619  
620     def __lt__(self, *args, **kwargs): # real signature unknown
621         """ Return self<value. """
622         pass
623  
624     def __mod__(self, *args, **kwargs): # real signature unknown
625         """ Return self%value. """
626         pass
627  
628     def __mul__(self, *args, **kwargs): # real signature unknown
629         """ Return self*value.n """
630         pass
631  
632     @staticmethod # known case of __new__
633     def __new__(*args, **kwargs): # real signature unknown
634         """ Create and return a new object.  See help(type) for accurate signature. """
635         pass
636  
637     def __ne__(self, *args, **kwargs): # real signature unknown
638         """ Return self!=value. """
639         pass
640  
641     def __repr__(self, *args, **kwargs): # real signature unknown
642         """ Return repr(self). """
643         pass
644  
645     def __rmod__(self, *args, **kwargs): # real signature unknown
646         """ Return value%self. """
647         pass
648  
649     def __rmul__(self, *args, **kwargs): # real signature unknown
650         """ Return self*value. """
651         pass
652  
653     def __sizeof__(self): # real signature unknown; restored from __doc__
654         """ S.__sizeof__() -> size of S in memory, in bytes """
655         pass
656  
657     def __str__(self, *args, **kwargs): # real signature unknown
658         """ Return str(self). """
659         pass
View Code

字符串索引,再看解压:

 1 msg='hello'
 2 #字符串索引操作
 3 print(msg[4])
 4 print(msg[-2])
 5 #字符串的切分操作
 6 print(msg[0:3]) #切分原则:顾头不顾尾
 7 print(msg[0:])
 8 print(msg[:3])
 9 print(msg[0:2000:2])#按两个字符切分
10 print(msg[::-1])#hello倒过来
11  
12 #再看变量解压操作
13 msg='hello'
14 x,y,z,*_=msg
15 print(x)
16 print(y)
17 print(z)
18 x,y,z='abc','aaa','xxx'
19 print(x)
20 print(y)
21 print(z)
View Code

三:列表

定义:

内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素

特性:

1.可存放多个值
2.可修改指定索引位置对应的值,可变
3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

1:列表的创建

1 name_list=['yyp','sy','lxh','zmh']或name_list=list('yyp')或name=list([’yyp','sy'])

列表常用方法

 1 name_list=['yyp','sy','lxh','zmh']
 2 #列表的索引操作
 3 print(name_list[-1])
 4 print(name_list[0:2])
 5 print(name_list[::-1])
 6 #列表的内置方法
 7 #append增加到末尾
 8 name_list=['yyp','sy','lxh','zmh']
 9 name_list.append('yy')
10 print(name_list)
11 #insert插入到指定位置
12 name_list=['yyp','sy','lxh','zmh']
13 name_list.insert(0,'ylqh')
14 print(name_list)
15 #pop删除<br>name_list.pop()#默认从右边删除
16 name_list.pop(2)#指定删除第二个
17 print(name_list)<br>
18 #清空列表
19 name_list=['yyp','sy','lxh','zmh']
20 name_list.clear()
21 print(name_list)
22  
23 #复制一份copy
24 name_list=['yyp','sy','lxh','zmh']
25 i=name_list.copy()
26 print(i)
27  
28 #计数
29 name_list=['yyp','yy','sy','lxh','zmh','yy','zzl']
30 print(name_list.count('yy'))#yy出现了几次
31  
32 #两个列表合并
33 name_list=['yyp','sy','lxh','zmh']
34 nlist=['ylqi','lift']
35 name_list.extend(nlist)
36 print(name_list)
37 #单独加入列表
38 every_lis='xxx'
39 name_list.extend(every_lis)
40 print(name_list)
41 <br>#remove移除
42 name_list=['yyp','sy','lxh','zmh']
43 name_list.remove(lxhl')#按照元素名移除,有多个重复的元素值时,移除第一个
44 print(name_list)
45  
46 #reverse反序排列<br>name_list=['yyp','sy','lxh','zmh']
47 name_list.reverse()#反序
48 print(name_list)
49 #sort排列
50 name_list=['d','c','A','1','@','*']
51 name_list.sort()#按照字符编码表排列
52 print(name_list)
53 #统计列表有几个元素或说成列表的长度
54 name_list=['yyp','sy','lxh','zmh']
55 print(len(name_list))#统计长度
56  
57 #判断是否在列表里面
58 # name_list=['yyp','sy','lxh','zmh']
59 print ('sy' in name_list)
60 print ('l' in name_list)
View Code

3:列表工厂函数

  1 class list(object):
  2     """
  3     list() -> new empty list
  4     list(iterable) -> new list initialized from iterable's items
  5     """
  6     def append(self, p_object): # real signature unknown; restored from __doc__
  7         """ L.append(object) -> None -- append object to end """
  8         pass
  9  
 10     def clear(self): # real signature unknown; restored from __doc__
 11         """ L.clear() -> None -- remove all items from L """
 12         pass
 13  
 14     def copy(self): # real signature unknown; restored from __doc__
 15         """ L.copy() -> list -- a shallow copy of L """
 16         return []
 17  
 18     def count(self, value): # real signature unknown; restored from __doc__
 19         """ L.count(value) -> integer -- return number of occurrences of value """
 20         return 0
 21  
 22     def extend(self, iterable): # real signature unknown; restored from __doc__
 23         """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
 24         pass
 25  
 26     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 27         """
 28         L.index(value, [start, [stop]]) -> integer -- return first index of value.
 29         Raises ValueError if the value is not present.
 30         """
 31         return 0
 32  
 33     def insert(self, index, p_object): # real signature unknown; restored from __doc__
 34         """ L.insert(index, object) -- insert object before index """
 35         pass
 36  
 37     def pop(self, index=None): # real signature unknown; restored from __doc__
 38         """
 39         L.pop([index]) -> item -- remove and return item at index (default last).
 40         Raises IndexError if list is empty or index is out of range.
 41         """
 42         pass
 43  
 44     def remove(self, value): # real signature unknown; restored from __doc__
 45         """
 46         L.remove(value) -> None -- remove first occurrence of value.
 47         Raises ValueError if the value is not present.
 48         """
 49         pass
 50  
 51     def reverse(self): # real signature unknown; restored from __doc__
 52         """ L.reverse() -- reverse *IN PLACE* """
 53         pass
 54  
 55     def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
 56         """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
 57         pass
 58  
 59     def __add__(self, *args, **kwargs): # real signature unknown
 60         """ Return self+value. """
 61         pass
 62  
 63     def __contains__(self, *args, **kwargs): # real signature unknown
 64         """ Return key in self. """
 65         pass
 66  
 67     def __delitem__(self, *args, **kwargs): # real signature unknown
 68         """ Delete self[key]. """
 69         pass
 70  
 71     def __eq__(self, *args, **kwargs): # real signature unknown
 72         """ Return self==value. """
 73         pass
 74  
 75     def __getattribute__(self, *args, **kwargs): # real signature unknown
 76         """ Return getattr(self, name). """
 77         pass
 78  
 79     def __getitem__(self, y): # real signature unknown; restored from __doc__
 80         """ x.__getitem__(y) <==> x[y] """
 81         pass
 82  
 83     def __ge__(self, *args, **kwargs): # real signature unknown
 84         """ Return self>=value. """
 85         pass
 86  
 87     def __gt__(self, *args, **kwargs): # real signature unknown
 88         """ Return self>value. """
 89         pass
 90  
 91     def __iadd__(self, *args, **kwargs): # real signature unknown
 92         """ Implement self+=value. """
 93         pass
 94  
 95     def __imul__(self, *args, **kwargs): # real signature unknown
 96         """ Implement self*=value. """
 97         pass
 98  
 99     def __init__(self, seq=()): # known special case of list.__init__
100         """
101         list() -> new empty list
102         list(iterable) -> new list initialized from iterable's items
103         # (copied from class doc)
104         """
105         pass
106  
107     def __iter__(self, *args, **kwargs): # real signature unknown
108         """ Implement iter(self). """
109         pass
110  
111     def __len__(self, *args, **kwargs): # real signature unknown
112         """ Return len(self). """
113         pass
114  
115     def __le__(self, *args, **kwargs): # real signature unknown
116         """ Return self<=value. """
117         pass
118  
119     def __lt__(self, *args, **kwargs): # real signature unknown
120         """ Return self<value. """
121         pass
122  
123     def __mul__(self, *args, **kwargs): # real signature unknown
124         """ Return self*value.n """
125         pass
126  
127     @staticmethod # known case of __new__
128     def __new__(*args, **kwargs): # real signature unknown
129         """ Create and return a new object.  See help(type) for accurate signature. """
130         pass
131  
132     def __ne__(self, *args, **kwargs): # real signature unknown
133         """ Return self!=value. """
134         pass
135  
136     def __repr__(self, *args, **kwargs): # real signature unknown
137         """ Return repr(self). """
138         pass
139  
140     def __reversed__(self): # real signature unknown; restored from __doc__
141         """ L.__reversed__() -- return a reverse iterator over the list """
142         pass
143  
144     def __rmul__(self, *args, **kwargs): # real signature unknown
145         """ Return self*value. """
146         pass
147  
148     def __setitem__(self, *args, **kwargs): # real signature unknown
149         """ Set self[key] to value. """
150         pass
151  
152     def __sizeof__(self): # real signature unknown; restored from __doc__
153         """ L.__sizeof__() -- size of L in memory, in bytes """
154         pass
155  
156     __hash__ = None
View Code

四:元组

定义:

与列表差不多,只不过[]改成(),同时也叫作只读列表

特性:

1.可以存多个值
2.不可变
3.按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

1:元组的创建

1 msg = (1,2,3,4,5)
2 ##或者
3 msg = tuple((1,2,3,4,5,6))

2:元组的常用方法

1 t=('yyp','sy',123)
2 print(t.count('sy'))#统计sy的次数
3 print(t.index('sy'))#统计sy的索引,没有则报错
4 print(len(t))#统计元组的长度
5 print('sy' in t) #包含,t是否包含sy

3:元组的工厂函数

  1 lass tuple(object):
  2     """
  3     tuple() -> empty tuple
  4     tuple(iterable) -> tuple initialized from iterable's items
  5      
  6     If the argument is a tuple, the return value is the same object.
  7     """
  8     def count(self, value): # real signature unknown; restored from __doc__
  9         """ T.count(value) -> integer -- return number of occurrences of value """
 10         return 0
 11  
 12     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 13         """
 14         T.index(value, [start, [stop]]) -> integer -- return first index of value.
 15         Raises ValueError if the value is not present.
 16         """
 17         return 0
 18  
 19     def __add__(self, y): # real signature unknown; restored from __doc__
 20         """ x.__add__(y) <==> x+y """
 21         pass
 22  
 23     def __contains__(self, y): # real signature unknown; restored from __doc__
 24         """ x.__contains__(y) <==> y in x """
 25         pass
 26  
 27     def __eq__(self, y): # real signature unknown; restored from __doc__
 28         """ x.__eq__(y) <==> x==y """
 29         pass
 30  
 31     def __getattribute__(self, name): # real signature unknown; restored from __doc__
 32         """ x.__getattribute__('name') <==> x.name """
 33         pass
 34  
 35     def __getitem__(self, y): # real signature unknown; restored from __doc__
 36         """ x.__getitem__(y) <==> x[y] """
 37         pass
 38  
 39     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 40         pass
 41  
 42     def __getslice__(self, i, j): # real signature unknown; restored from __doc__
 43         """
 44         x.__getslice__(i, j) <==> x[i:j]
 45                     
 46                    Use of negative indices is not supported.
 47         """
 48         pass
 49  
 50     def __ge__(self, y): # real signature unknown; restored from __doc__
 51         """ x.__ge__(y) <==> x>=y """
 52         pass
 53  
 54     def __gt__(self, y): # real signature unknown; restored from __doc__
 55         """ x.__gt__(y) <==> x>y """
 56         pass
 57  
 58     def __hash__(self): # real signature unknown; restored from __doc__
 59         """ x.__hash__() <==> hash(x) """
 60         pass
 61  
 62     def __init__(self, seq=()): # known special case of tuple.__init__
 63         """
 64         tuple() -> empty tuple
 65         tuple(iterable) -> tuple initialized from iterable's items
 66          
 67         If the argument is a tuple, the return value is the same object.
 68         # (copied from class doc)
 69         """
 70         pass
 71  
 72     def __iter__(self): # real signature unknown; restored from __doc__
 73         """ x.__iter__() <==> iter(x) """
 74         pass
 75  
 76     def __len__(self): # real signature unknown; restored from __doc__
 77         """ x.__len__() <==> len(x) """
 78         pass
 79  
 80     def __le__(self, y): # real signature unknown; restored from __doc__
 81         """ x.__le__(y) <==> x<=y """
 82         pass
 83  
 84     def __lt__(self, y): # real signature unknown; restored from __doc__
 85         """ x.__lt__(y) <==> x<y """
 86         pass
 87  
 88     def __mul__(self, n): # real signature unknown; restored from __doc__
 89         """ x.__mul__(n) <==> x*n """
 90         pass
 91  
 92     @staticmethod # known case of __new__
 93     def __new__(S, *more): # real signature unknown; restored from __doc__
 94         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
 95         pass
 96  
 97     def __ne__(self, y): # real signature unknown; restored from __doc__
 98         """ x.__ne__(y) <==> x!=y """
 99         pass
100  
101     def __repr__(self): # real signature unknown; restored from __doc__
102         """ x.__repr__() <==> repr(x) """
103         pass
104  
105     def __rmul__(self, n): # real signature unknown; restored from __doc__
106         """ x.__rmul__(n) <==> n*x """
107         pass
108  
109     def __sizeof__(self): # real signature unknown; restored from __doc__
110         """ T.__sizeof__() -- size of T in memory, in bytes """
111         pass
View Code

4:元组的不可变行eg

1 t = ('yyp', 'sy', ['YYP', 'SY'])
2 print(t)
3 t[2][0] = 'Y'
4 t[2][1] = 'S'
5 print(t)
6  
7 输出信息:
8 ('yyp', 'sy', ['YYP', 'SY'])
9 ('yyp', 'sy', ['Y', 'S'])

五:字典

定义:

{key:value},key-value 形式,key必须可hash

特性:

1.可存放多个值

2.可修改指定key对应的值,可变

3.无序

4.可变类型不能当做字典的key,value可以是任何数据类型

5.key不能重复

1:字典的创建

 1 dic={'name1':'yyp','name2':'sy'}
 2 或者
 3 dic1={(1,2,3):'aa'} #元组可以当做key
 4 或者
 5 dic2 = dict(name='yyp', age=16)
 6 或者
 7 dic3 = dict({"name": "yyp", 'age': 28})
 8 或者
 9 dic4 = dict((['name','yyp'],['age',120]))
10  
11 输出结果:
12 {'name1': 'yyp', 'name2': 'sy'}
13 {(1, 2, 3): 'aa'}
14 {'name': 'yyp', 'age': 16}
15 {'name': 'yyp', 'age': 28}
16 {'name': 'yyp', 'age': 20}
View Code

2:字典的常用方法

 1 取值:
 2 info={'msg1':'yyp','msg2':'sy','msg3':'yp','msg4':'yy'}
 3 print('msg1' in info) #标准用法,存在返回True,不存在返回False
 4 print(info.get('msg2'))  #获取
 5 print(info['msg2']) #获取的到的时候,取值
 6  
 7 print(info['msg8'])#一旦获取不到,则报错
 8  
 9 输出结果:
10 True
11 sy
12 sy
13  
14 Traceback (most recent call last):
15   File "D:/my/python script/untitled/dict.py", line 21, in <module>
16     print(info['msg8'])#一旦获取不到,则报错
17 KeyError: 'msg8'
18  
19  
20 #增加
21 info={'msg1':'yyp','msg2':'sy'}
22 print(info)
23 info['msg3'] = 'yp'#增加
24 print(info)
25  
26 结果:
27 {'msg1': 'yyp', 'msg2': 'sy'}
28 {'msg1': 'yyp', 'msg2': 'sy', 'msg3': 'yp'}
29  
30  
31 #修改:
32 info={'msg1':'yyp','msg2':'sy'}
33 print(info)
34 info['msg2'] = 'yy' #修改
35 print(info)
36  
37 结果:
38 {'msg1': 'yyp', 'msg2': 'sy'}
39 {'msg1': 'yyp', 'msg2': 'yy'}
40  
41  
42 一下五个都为删除用法:
43 info={'msg1':'yyp','msg2':'sy','msg3':'yp','msg4':'yy'}
44 print(info)
45 info.pop('msg3')
46 print(info)
47 del info['msg2']
48 print(info)
49 info.popitem()# 随机删除一个
50 print(info)
51  
52 info.clear() #整个列表清空
53 print(info)
54  
55 结果:
56 {'msg1': 'yyp', 'msg2': 'sy', 'msg3': 'yp', 'msg4': 'yy'}
57 {'msg1': 'yyp', 'msg2': 'sy', 'msg4': 'yy'}
58 {'msg1': 'yyp', 'msg4': 'yy'}
59 {'msg1': 'yyp'}
60 {}
View Code

3.字典的其他操作:

多级字典嵌套:

 1 dict_name = {
 2     "msg1":{
 3         "name1": ["","one"],
 4         "name2": ["","two"],
 5     },
 6     "msg2":{
 7         "name3":["li","whree"]
 8     },
 9     "msg3":{
10         "name4":["","four"]
11     }
12 }
13  
14 dict_name["msg2"]["name3"][1] += ",你好"
15 print(dict_name["msg2"]["name3"])
16  
17 输出结果:
18 ['li', 'whree,你好']
View Code

4:字典的工厂函数

  1 class dict(object):
  2     """
  3     dict() -> new empty dictionary
  4     dict(mapping) -> new dictionary initialized from a mapping object's
  5         (key, value) pairs
  6     dict(iterable) -> new dictionary initialized as if via:
  7         d = {}
  8         for k, v in iterable:
  9             d[k] = v
 10     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 11         in the keyword argument list.  For example:  dict(one=1, two=2)
 12     """
 13  
 14     def clear(self): # real signature unknown; restored from __doc__
 15         """ 清除内容 """
 16         """ D.clear() -> None.  Remove all items from D. """
 17         pass
 18  
 19     def copy(self): # real signature unknown; restored from __doc__
 20         """ 浅拷贝 """
 21         """ D.copy() -> a shallow copy of D """
 22         pass
 23  
 24     @staticmethod # known case
 25     def fromkeys(S, v=None): # real signature unknown; restored from __doc__
 26         """
 27         dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
 28         v defaults to None.
 29         """
 30         pass
 31  
 32     def get(self, k, d=None): # real signature unknown; restored from __doc__
 33         """ 根据key获取值,d是默认值 """
 34         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
 35         pass
 36  
 37     def has_key(self, k): # real signature unknown; restored from __doc__
 38         """ 是否有key """
 39         """ D.has_key(k) -> True if D has a key k, else False """
 40         return False
 41  
 42     def items(self): # real signature unknown; restored from __doc__
 43         """ 所有项的列表形式 """
 44         """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
 45         return []
 46  
 47     def iteritems(self): # real signature unknown; restored from __doc__
 48         """ 项可迭代 """
 49         """ D.iteritems() -> an iterator over the (key, value) items of D """
 50         pass
 51  
 52     def iterkeys(self): # real signature unknown; restored from __doc__
 53         """ key可迭代 """
 54         """ D.iterkeys() -> an iterator over the keys of D """
 55         pass
 56  
 57     def itervalues(self): # real signature unknown; restored from __doc__
 58         """ value可迭代 """
 59         """ D.itervalues() -> an iterator over the values of D """
 60         pass
 61  
 62     def keys(self): # real signature unknown; restored from __doc__
 63         """ 所有的key列表 """
 64         """ D.keys() -> list of D's keys """
 65         return []
 66  
 67     def pop(self, k, d=None): # real signature unknown; restored from __doc__
 68         """ 获取并在字典中移除 """
 69         """
 70         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 71         If key is not found, d is returned if given, otherwise KeyError is raised
 72         """
 73         pass
 74  
 75     def popitem(self): # real signature unknown; restored from __doc__
 76         """ 获取并在字典中移除 """
 77         """
 78         D.popitem() -> (k, v), remove and return some (key, value) pair as a
 79         2-tuple; but raise KeyError if D is empty.
 80         """
 81         pass
 82  
 83     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
 84         """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
 85         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
 86         pass
 87  
 88     def update(self, E=None, **F): # known special case of dict.update
 89         """ 更新
 90             {'name':'alex', 'age': 18000}
 91             [('name','sbsbsb'),]
 92         """
 93         """
 94         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 95         If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
 96         If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
 97         In either case, this is followed by: for k in F: D[k] = F[k]
 98         """
 99         pass
100  
101     def values(self): # real signature unknown; restored from __doc__
102         """ 所有的值 """
103         """ D.values() -> list of D's values """
104         return []
105  
106     def viewitems(self): # real signature unknown; restored from __doc__
107         """ 所有项,只是将内容保存至view对象中 """
108         """ D.viewitems() -> a set-like object providing a view on D's items """
109         pass
110  
111     def viewkeys(self): # real signature unknown; restored from __doc__
112         """ D.viewkeys() -> a set-like object providing a view on D's keys """
113         pass
114  
115     def viewvalues(self): # real signature unknown; restored from __doc__
116         """ D.viewvalues() -> an object providing a view on D's values """
117         pass
118  
119     def __cmp__(self, y): # real signature unknown; restored from __doc__
120         """ x.__cmp__(y) <==> cmp(x,y) """
121         pass
122  
123     def __contains__(self, k): # real signature unknown; restored from __doc__
124         """ D.__contains__(k) -> True if D has a key k, else False """
125         return False
126  
127     def __delitem__(self, y): # real signature unknown; restored from __doc__
128         """ x.__delitem__(y) <==> del x[y] """
129         pass
130  
131     def __eq__(self, y): # real signature unknown; restored from __doc__
132         """ x.__eq__(y) <==> x==y """
133         pass
134  
135     def __getattribute__(self, name): # real signature unknown; restored from __doc__
136         """ x.__getattribute__('name') <==> x.name """
137         pass
138  
139     def __getitem__(self, y): # real signature unknown; restored from __doc__
140         """ x.__getitem__(y) <==> x[y] """
141         pass
142  
143     def __ge__(self, y): # real signature unknown; restored from __doc__
144         """ x.__ge__(y) <==> x>=y """
145         pass
146  
147     def __gt__(self, y): # real signature unknown; restored from __doc__
148         """ x.__gt__(y) <==> x>y """
149         pass
150  
151     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
152         """
153         dict() -> new empty dictionary
154         dict(mapping) -> new dictionary initialized from a mapping object's
155             (key, value) pairs
156         dict(iterable) -> new dictionary initialized as if via:
157             d = {}
158             for k, v in iterable:
159                 d[k] = v
160         dict(**kwargs) -> new dictionary initialized with the name=value pairs
161             in the keyword argument list.  For example:  dict(one=1, two=2)
162         # (copied from class doc)
163         """
164         pass
165  
166     def __iter__(self): # real signature unknown; restored from __doc__
167         """ x.__iter__() <==> iter(x) """
168         pass
169  
170     def __len__(self): # real signature unknown; restored from __doc__
171         """ x.__len__() <==> len(x) """
172         pass
173  
174     def __le__(self, y): # real signature unknown; restored from __doc__
175         """ x.__le__(y) <==> x<=y """
176         pass
177  
178     def __lt__(self, y): # real signature unknown; restored from __doc__
179         """ x.__lt__(y) <==> x<y """
180         pass
181  
182     @staticmethod # known case of __new__
183     def __new__(S, *more): # real signature unknown; restored from __doc__
184         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
185         pass
186  
187     def __ne__(self, y): # real signature unknown; restored from __doc__
188         """ x.__ne__(y) <==> x!=y """
189         pass
190  
191     def __repr__(self): # real signature unknown; restored from __doc__
192         """ x.__repr__() <==> repr(x) """
193         pass
194  
195     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
196         """ x.__setitem__(i, y) <==> x[i]=y """
197         pass
198  
199     def __sizeof__(self): # real signature unknown; restored from __doc__
200         """ D.__sizeof__() -> size of D in memory, in bytes """
201         pass
202  
203     __hash__ = None
View Code

六、集合

1:集合的创建

1 msg = set([1,2,3])#创建一个数值的集合
2 print(msg)
3 或者
4 msg = set("hello")#创建一个唯一字符的集合
5 print(msg)
6  
7 输出结果:
8 {1, 2, 3}
9 {'h', 'e', 'o', 'l'}

2:集合的常用操作

 1 msg = set([1, 1, 2, 2, 3, 3])#重复的元素自动过滤掉
 2 print(msg)
 3  
 4 结果:
 5 {1, 2, 3}
 6  
 7 msg.add(8) #可以添加元素到set中,可以重复添加,但是没有任何效果哦
 8 print(msg)
 9  
10 结果:
11 {8, 1, 2, 3}
12  
13 msg.remove(1)#删除set中的元素
14 print(msg)
15  
16 结果:
17 {8, 2, 3}
18  
19 msg.update([5,8,6])#在set中添加多项
20 print(msg)
21  
22 结果:
23 {2, 3, 5, 6, 8}
24  
25 print(len(msg))#set的长度
26 结果:
27 5
View Code

set关系运算

 1 msg1 = set([2, 3, 5, 6, 8])
 2 msg2 = set([1,3,5])
 3 print(1 in msg1) #测试1是否是msg1的成员,是则返回True,否则返回False
 4  
 5 输出结果:
 6 False
 7  
 8 print(1 not in msg1) #测试1是否不是msg1的成员,是则返回False,不是返回True
 9  
10 输出结果:
11 True
12  
13 #测试是否msg2中的每一个元素都在msg1中
14 print(msg2.issubset(msg1))
15 print(msg2 <= msg1)
16  
17 输出结果:
18 False
19 False
20  
21 #测试msg1中的每个元素都在msg2中
22 print(msg2.issuperset(msg1))
23 print(msg2 >= msg1)
24  
25 输出结果:
26 False
27 False
28  
29 #返回一个新的set包含msg1和msg2的每一个元素
30 print(msg2.union(msg1))
31 print(msg2 | msg1)
32  
33 输出结果:
34 {1, 2, 3, 5, 6, 8}
35 {1, 2, 3, 5, 6, 8}
36  
37 #返回一个新的set包含msg1与msg2的公共元素
38 print(msg2.intersection(msg1))
39 print(msg1 & msg2)
40  
41 输出结果:
42 {3, 5}
43 {3, 5}
44  
45 #返回一个新的set包含msg2中有但是msg1中没有的元素
46 print(msg2.difference(msg1))
47 print(msg2 - msg1)
48  
49 输出结果:
50 {1}
51 {1}
52  
53 #返回一个新的set包含msg2和msg1中不重复的元素
54 print(msg2.symmetric_difference(msg1))
55 print(msg2 ^ msg1)
56  
57 输出结果:
58 {1, 2, 6, 8}
59 {1, 2, 6, 8}
60  
61 #返回set “msg1”的一个浅的复制
62 print(msg1.copy())
63  
64 输出结果:
65 {8, 2, 3, 5, 6}
View Code

set做交集、并集等操作

msg1 = set([1,3,5])
msg2 = set([1,2,3])
 
print(msg1 & msg2) #msg1与msg2的交集
print(msg1| msg2 ) #msg1与msg2的并集
print(msg1 - msg2) #求差集(元素在msg1中,但不在msg2中)
print(msg1 ^ msg2) #对称差集(元素在msg1或msg2中,但不会同时出现在二者中)
 
输出结果:
 
{1, 3}
{1, 2, 3, 5}
{5}
{2, 5}
View Code

3:集合工厂

  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
View Code

 

循环区别:

字符串循环:

 1 #字符串循环:
 2 方法1:
 3 msg='love'
 4 for i in msg:
 5     print(i)
 6  
 7 结果:
 8 l
 9 o
10 v
11 e
12  
13 方法2:
14 for i in enumerate(msg):
15     print(i)
16  
17 结果:
18 (0, 'l')
19 (1, 'o')
20 (2, 'v')
21 (3, 'e')
22  
23 方法3:倒叙循环
24 for i in msg[::-1]:
25     print(i)
View Code

列表循环:

 1 lis=['yyp','sy','yy']
 2 for i in lis:
 3     print(i)
 4  
 5 for i in enumerate(lis):
 6     print(i)
 7  
 8 结果:
 9 yyp
10 sy
11 yy
12 (0, 'yyp')
13 (1, 'sy')
14 (2, 'yy')
View Code

元组循环:

 1 tup=('x','y','z')
 2 for i in tup:
 3     print(i)
 4  
 5 for i in enumerate(tup):
 6     print(i)
 7  
 8 结果:
 9 x
10 y
11 z
12 (0, 'x')
13 (1, 'y')
14 (2, 'z')
View Code

字典循环:

 1 #字典循环
 2 info={'msg1':'yyp','msg2':'sy','msg3':'zl','msg4':'yy'}
 3 #方法1
 4 for key in info:
 5     print(key,info[key])
 6   
 7 结果
 8 msg1 yyp
 9 msg2 sy
10 msg3 zl
11 msg4 yy
12   
13 #方法2
14 for k,v in info.items(): #会先把dict转成list,数据大时最好不要用
15     print(k,v)
16   
17 结果:
18 msg1 yyp
19 msg2 sy
20 msg3 zl
21 msg4 yy
22  
23 info={'name1':'yyp','name2':'sy','name3':'yy'}
24 方法3:
25 info={'name1':'yyp','name2':'sy','name3':'yy'}
26 for i in enumerate(info):
27     print(i)
28  
29 结果:
30 (0, 'name1')
31 (1, 'name2')
32 (2, 'name3')
33  
34 方法4:
35 for i in info.keys():
36     print(i,info[i])
37  
38 结果:
39 name1 yyp
40 name2 sy
41 name3 yy
42  
43 方法5:
44 for v in info.values():
45     print(v)
46  
47 结果:
48 yyp
49 sy
50 yy
View Code

 列表转为其他类型:

 列表不可以转为字典

 1 nums=[1,3,5,7,8,0]
 2  
 3 #列表转为字符串:
 4 print(str(nums),type(str(nums)))
 5  
 6 结果:
 7 [1, 3, 5, 7, 8, 0] <class 'str'>
 8  
 9 #列表转为元组:
10 print(tuple(nums),type(tuple(nums)))
11 结果:
12 (1, 3, 5, 7, 8, 0) <class 'tuple'>
View Code

元组转为其他类型:

元组不可以转为字典

 1 tup=(1, 2, 3, 4, 5)
 2  
 3 #元组转为字符串
 4 print(tup.__str__(),type(tup.__str__()))
 5  
 6 结果:
 7 (1, 2, 3, 4, 5) <class 'str'>
 8  
 9 #元组转为列表
10 print(list(tup),type(list(tup)))
11  
12 结果:
13 [1, 2, 3, 4, 5] <class 'list'>
View Code

字典转为其他类型:

 1 dic = {'name': 'Zara', 'age': 7, 'class': 'First'}
 2  
 3 #字典转为字符串
 4 print(str(dic),type(str(dic)))
 5  
 6 结果:
 7 {'age': 7, 'name': 'Zara', 'class': 'First'} <class 'str'>
 8  
 9 #字典可以转为元组
10 print(tuple(dic),type(tuple(dic)))
11 #字典可以转为元组
12 print(tuple(dic.values()),type(tuple(dic.values())))
13  
14 结果:
15 ('age', 'name', 'class') <class 'tuple'>
16 (7, 'Zara', 'First') <class 'tuple'>
17  
18 #字典转为列表
19 print(list(dic),type(list(dic)))
20 #字典转为列表
21 print(list(dic.values()),type(list(dic.values())))
22  
23 结果:
24 ['age', 'name', 'class'] <class 'list'>
25 [7, 'Zara', 'First'] <class 'list'>
26 分类: python
View Code

总结

1.按存值个数区分

标量/原子类型 数字,字符串
容器类型 列表,元组,字典

2.按可变不可变区分

可变 列表,字典
不可变 数字,字符串,元组

证明:可变/不可变

更改数据类型其中的元素,如果内存地址发生变化,则为不可变类型,如果内存地址没有发生变化,则为可变类型。

详情参考:http://www.cnblogs.com/ylqh/p/6388330.html 的内存管理

3.按访问顺序区分

直接访问 数字
顺序访问(序列类型) 字符串,列表,元组
key值访问(映射类型) 字典

补充:字典占用的内存空间比列表大,(因为要在内存空间保存一端时间的hash表)但是字典查询速度比列表快,联想到非关系型数据库比关系型数据查询要快应该就会想明白。

原文地址:https://www.cnblogs.com/Vae1242/p/6940152.html