Python学习之路——day02

入门知识拾遗

一、作用域

在Python中,变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用。

1 >>> if 1 == 1:
2 ...   name = 'ghost';
3 ... 
4 >>> print name
5 ghost
6 >>> 

下面有一个网上的总结,用上面的例子可以证明是有误的——

外层变量,可以被内层变量使用
内层变量,无法被外层变量使用

二、三元运算

三元运算,又叫三目运算,就是if语句的一种简单写法

 1 #格式如下,左边是变量名,右边是表达式,如果表达式为真,就返回if前面那个值,否则就返回else后面的值
 2 >>> result = 'OK' if 1 == 1 else 'NO'
 3 >>> print result
 4 OK
 5 #下面是用正常的if语句写的,可以看到三元运算方式比较简便
 6 >>> if 1 == 1:
 7 ...   result = 'OK';
 8 ... else:
 9 ...   result = 'NO';
10 ... 
11 >>> print result
12 OK
13 >>> 

如果条件为真:result的值为‘OK’;
如果条件为假:result的值为‘NO’;

三、进制

  •  二进制:0101
  • 八进制:01234567
  • 十进制:0123456789
  • 十六进制:0123456789ABCDE

Python基础

在Python中,一切事件皆对象,对象基于类创建

Python学习之路——day02_第1张图片

所以,以下这些值都是对象:'ghost'、33、['a','b',11],并且是根据不同的类生成的对象。

Python学习之路——day02_第2张图片

小知识:在IDE中快速查看Python的源码

如在PyCharm中,新建一个.py文件,然后在里面敲如“int”,然后按“Ctrl”键,用鼠标左键点击,就能定位到了,如下截图

一、整数

如:11、3333、909

每一个整数都具备如下功能:

  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         """ 返回表示该数字的时占用的最少位数,下面的例子很详细,0b代表二进制,
 19             也就是说用二进制表示时占用的最少位数。"""
 20         """
 21         int.bit_length() -> int
 22         
 23         Number of bits necessary to represent self in binary.
 24         >>> bin(37)
 25         '0b100101'
 26         >>> (37).bit_length()
 27         """
 28         return 0
 29 
 30     def conjugate(self, *args, **kwargs): # real signature unknown
 31         """ 返回该复数的共轭复数 这个不知道是什么意思 """
 32         """ Returns self, the complex conjugate of any int. """
 33         pass
 34 
 35     def __abs__(self):
 36         """ 返回绝对值 等价于后面的abs(x)方法 """
 37         """ x.__abs__() <==> abs(x) """
 38         pass
 39 
 40     def __add__(self, y):
 41         """ 就是加法 """
 42         """ x.__add__(y) <==> x+y """
 43         pass
 44 
 45     def __and__(self, y):
 46         """ 位与运算 """
 47         """ x.__and__(y) <==> x&y """
 48         pass
 49 
 50     def __cmp__(self, y): 
 51         """ 比较两个数大小 """
 52         """ x.__cmp__(y) <==> cmp(x,y) """
 53         pass
 54 
 55     def __coerce__(self, y):
 56         """ 强制生成一个元组 """ 
 57         """ x.__coerce__(y) <==> coerce(x, y) """
 58         pass
 59 
 60     def __divmod__(self, y): 
 61         """ 相除,得到商和余数组成的元组 """
 62         """ 所说这个可以做分页,如计算显示多少页 """
 63         """ x.__divmod__(y) <==> divmod(x, y) """
 64         pass
 65 
 66     def __div__(self, y): 
 67         """ 两数相除 """
 68         """ x.__div__(y) <==> x/y """
 69         pass
 70 
 71     def __float__(self): 
 72         """ 转换为浮点类型 """ 
 73         """ x.__float__() <==> float(x) """
 74         pass
 75 
 76     def __floordiv__(self, y): 
 77         """ x.__floordiv__(y) <==> x//y """
 78         ''' 浮点类型相除时只保留整数位
 79         >>> 10.0//4
 80         2.0
 81         >>> 10.0/4
 82         2.5
 83         >>> 
 84         '''
 85         pass
 86 
 87     def __format__(self, *args, **kwargs): # real signature unknown
 88         pass
 89 
 90     def __getattribute__(self, name): 
 91         """ x.__getattribute__('name') <==> x.name """
 92         pass
 93 
 94     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 95         """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
 96         pass
 97 
 98     def __hash__(self): 
 99         """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
100         """ x.__hash__() <==> hash(x) """
101         pass
102 
103     def __hex__(self): 
104         """ 返回当前数的 十六进制 表示 """ 
105         """ x.__hex__() <==> hex(x) """
106         pass
107 
108     def __index__(self): 
109         """ 用于切片,数字无意义 """
110         """ x[y:z] <==> x[y.__index__():z.__index__()] """
111         pass
112 
113     def __init__(self, x, base=10): # known special case of int.__init__
114         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
115         """
116         int(x=0) -> int or long
117         int(x, base=10) -> int or long
118         
119         Convert a number or string to an integer, or return 0 if no arguments
120         are given.  If x is floating point, the conversion truncates towards zero.
121         If x is outside the integer range, the function returns a long instead.
122         
123         If x is not a number or if base is given, then x must be a string or
124         Unicode object representing an integer literal in the given base.  The
125         literal can be preceded by '+' or '-' and be surrounded by whitespace.
126         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
127         interpret the base from the string as an integer literal.
128         >>> int('0b100', base=0)
129         # (copied from class doc)
130         """
131         pass
132 
133     def __int__(self): 
134         """ 转换为整数 """ 
135         """ x.__int__() <==> int(x) """
136         pass
137 
138     def __invert__(self): 
139         """ x.__invert__() <==> ~x """
140         pass
141 
142     def __long__(self): 
143         """ 转换为长整数 """ 
144         """ x.__long__() <==> long(x) """
145         pass
146 
147     def __lshift__(self, y): 
148         """ x.__lshift__(y) <==> x<"""
149         pass
150 
151     def __mod__(self, y): 
152         """ x.__mod__(y) <==> x%y """
153         pass
154 
155     def __mul__(self, y): 
156         """ x.__mul__(y) <==> x*y """
157         pass
158 
159     def __neg__(self): 
160         """ x.__neg__() <==> -x """
161         pass
162 
163     @staticmethod # known case of __new__
164     def __new__(S, *more): 
165         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
166         pass
167 
168     def __nonzero__(self): 
169         """ x.__nonzero__() <==> x != 0 """
170         pass
171 
172     def __oct__(self): 
173         """ 返回改值的 八进制 表示 """ 
174         """ x.__oct__() <==> oct(x) """
175         pass
176 
177     def __or__(self, y): 
178         """ x.__or__(y) <==> x|y """
179         pass
180 
181     def __pos__(self): 
182         """ x.__pos__() <==> +x """
183         pass
184 
185     def __pow__(self, y, z=None): 
186         """ 幂,次方 
187         >>> a=10
188         >>> b=2
189         >>> a.__po
190         >>> a.__pow__(b)
191         100
192         >>> pow(a,b)
193         100
194         >>> 
195         """ 
196         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
197         pass
198 
199     def __radd__(self, y): 
200         """ x.__radd__(y) <==> y+x """
201         pass
202 
203     def __rand__(self, y): 
204         """ x.__rand__(y) <==> y&x """
205         pass
206 
207     def __rdivmod__(self, y): 
208         """ x.__rdivmod__(y) <==> divmod(y, x) """
209         pass
210 
211     def __rdiv__(self, y): 
212         """ x.__rdiv__(y) <==> y/x """
213         pass
214 
215     def __repr__(self): 
216         """转化为解释器可读取的形式 """
217         """ x.__repr__() <==> repr(x) """
218         pass
219 
220     def __str__(self): 
221         """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
222         """ x.__str__() <==> str(x) """
223         pass
224 
225     def __rfloordiv__(self, y): 
226         """ x.__rfloordiv__(y) <==> y//x """
227         pass
228 
229     def __rlshift__(self, y): 
230         """ x.__rlshift__(y) <==> y<"""
231         pass
232 
233     def __rmod__(self, y): 
234         """ x.__rmod__(y) <==> y%x """
235         pass
236 
237     def __rmul__(self, y): 
238         """ x.__rmul__(y) <==> y*x """
239         pass
240 
241     def __ror__(self, y): 
242         """ x.__ror__(y) <==> y|x """
243         pass
244 
245     def __rpow__(self, x, z=None): 
246         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
247         pass
248 
249     def __rrshift__(self, y): 
250         """ x.__rrshift__(y) <==> y>>x """
251         pass
252 
253     def __rshift__(self, y): 
254         """ x.__rshift__(y) <==> x>>y """
255         pass
256 
257     def __rsub__(self, y): 
258         """ x.__rsub__(y) <==> y-x """
259         pass
260 
261     def __rtruediv__(self, y): 
262         """ x.__rtruediv__(y) <==> y/x """
263         pass
264 
265     def __rxor__(self, y): 
266         """ x.__rxor__(y) <==> y^x """
267         pass
268 
269     def __sub__(self, y): 
270         """ x.__sub__(y) <==> x-y """
271         pass
272 
273     def __truediv__(self, y): 
274         """ x.__truediv__(y) <==> x/y """
275         pass
276 
277     def __trunc__(self, *args, **kwargs): 
278         """ 返回数值被截取为整形的值,在整形中无意义 """
279         pass
280 
281     def __xor__(self, y): 
282         """ x.__xor__(y) <==> x^y """
283         pass
284 
285     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
286     """ 分母 = 1 """
287     """the denominator of a rational number in lowest terms"""
288 
289     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
290     """ 虚数,无意义 """
291     """the imaginary part of a complex number"""
292 
293     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
294     """ 分子 = 数字大小 """
295     """the numerator of a rational number in lowest terms"""
296 
297     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
298     """ 实属,无意义 """
299     """the real part of a complex number"""
int

 二、长整型

可能是:6549645816313123213546351464856546、111111111111111111111111111这类的大数

每个长整型都具备如下功能:

  1 class long(object):
  2     """
  3     长整型的方法和int类的方法差不多,可以看到很多都是相同的方法名
  4     long(x=0) -> long
  5     long(x, base=10) -> long
  6     
  7     Convert a number or string to a long integer, or return 0L if no arguments
  8     are given.  If x is floating point, the conversion truncates towards zero.
  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     4L
 17     """
 18     def bit_length(self): # real signature unknown; restored from __doc__
 19         """
 20         long.bit_length() -> int or long
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37L)
 24         '0b100101'
 25         >>> (37L).bit_length()
 26         """
 27         return 0
 28 
 29     def conjugate(self, *args, **kwargs): # real signature unknown
 30         """ Returns self, the complex conjugate of any long. """
 31         pass
 32 
 33     def __abs__(self): # real signature unknown; restored from __doc__
 34         """ x.__abs__() <==> abs(x) """
 35         pass
 36 
 37     def __add__(self, y): # real signature unknown; restored from __doc__
 38         """ x.__add__(y) <==> x+y """
 39         pass
 40 
 41     def __and__(self, y): # real signature unknown; restored from __doc__
 42         """ x.__and__(y) <==> x&y """
 43         pass
 44 
 45     def __cmp__(self, y): # real signature unknown; restored from __doc__
 46         """ x.__cmp__(y) <==> cmp(x,y) """
 47         pass
 48 
 49     def __coerce__(self, y): # real signature unknown; restored from __doc__
 50         """ x.__coerce__(y) <==> coerce(x, y) """
 51         pass
 52 
 53     def __divmod__(self, y): # real signature unknown; restored from __doc__
 54         """ x.__divmod__(y) <==> divmod(x, y) """
 55         pass
 56 
 57     def __div__(self, y): # real signature unknown; restored from __doc__
 58         """ x.__div__(y) <==> x/y """
 59         pass
 60 
 61     def __float__(self): # real signature unknown; restored from __doc__
 62         """ x.__float__() <==> float(x) """
 63         pass
 64 
 65     def __floordiv__(self, y): # real signature unknown; restored from __doc__
 66         """ x.__floordiv__(y) <==> x//y """
 67         pass
 68 
 69     def __format__(self, *args, **kwargs): # real signature unknown
 70         pass
 71 
 72     def __getattribute__(self, name): # real signature unknown; restored from __doc__
 73         """ x.__getattribute__('name') <==> x.name """
 74         pass
 75 
 76     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 77         pass
 78 
 79     def __hash__(self): # real signature unknown; restored from __doc__
 80         """ x.__hash__() <==> hash(x) """
 81         pass
 82 
 83     def __hex__(self): # real signature unknown; restored from __doc__
 84         """ x.__hex__() <==> hex(x) """
 85         pass
 86 
 87     def __index__(self): # real signature unknown; restored from __doc__
 88         """ x[y:z] <==> x[y.__index__():z.__index__()] """
 89         pass
 90 
 91     def __init__(self, x=0): # real signature unknown; restored from __doc__
 92         pass
 93 
 94     def __int__(self): # real signature unknown; restored from __doc__
 95         """ x.__int__() <==> int(x) """
 96         pass
 97 
 98     def __invert__(self): # real signature unknown; restored from __doc__
 99         """ x.__invert__() <==> ~x """
100         pass
101 
102     def __long__(self): # real signature unknown; restored from __doc__
103         """ x.__long__() <==> long(x) """
104         pass
105 
106     def __lshift__(self, y): # real signature unknown; restored from __doc__
107         """ x.__lshift__(y) <==> x<"""
108         pass
109 
110     def __mod__(self, y): # real signature unknown; restored from __doc__
111         """ x.__mod__(y) <==> x%y """
112         pass
113 
114     def __mul__(self, y): # real signature unknown; restored from __doc__
115         """ x.__mul__(y) <==> x*y """
116         pass
117 
118     def __neg__(self): # real signature unknown; restored from __doc__
119         """ x.__neg__() <==> -x """
120         pass
121 
122     @staticmethod # known case of __new__
123     def __new__(S, *more): # real signature unknown; restored from __doc__
124         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
125         pass
126 
127     def __nonzero__(self): # real signature unknown; restored from __doc__
128         """ x.__nonzero__() <==> x != 0 """
129         pass
130 
131     def __oct__(self): # real signature unknown; restored from __doc__
132         """ x.__oct__() <==> oct(x) """
133         pass
134 
135     def __or__(self, y): # real signature unknown; restored from __doc__
136         """ x.__or__(y) <==> x|y """
137         pass
138 
139     def __pos__(self): # real signature unknown; restored from __doc__
140         """ x.__pos__() <==> +x """
141         pass
142 
143     def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
144         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
145         pass
146 
147     def __radd__(self, y): # real signature unknown; restored from __doc__
148         """ x.__radd__(y) <==> y+x """
149         pass
150 
151     def __rand__(self, y): # real signature unknown; restored from __doc__
152         """ x.__rand__(y) <==> y&x """
153         pass
154 
155     def __rdivmod__(self, y): # real signature unknown; restored from __doc__
156         """ x.__rdivmod__(y) <==> divmod(y, x) """
157         pass
158 
159     def __rdiv__(self, y): # real signature unknown; restored from __doc__
160         """ x.__rdiv__(y) <==> y/x """
161         pass
162 
163     def __repr__(self): # real signature unknown; restored from __doc__
164         """ x.__repr__() <==> repr(x) """
165         pass
166 
167     def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
168         """ x.__rfloordiv__(y) <==> y//x """
169         pass
170 
171     def __rlshift__(self, y): # real signature unknown; restored from __doc__
172         """ x.__rlshift__(y) <==> y<"""
173         pass
174 
175     def __rmod__(self, y): # real signature unknown; restored from __doc__
176         """ x.__rmod__(y) <==> y%x """
177         pass
178 
179     def __rmul__(self, y): # real signature unknown; restored from __doc__
180         """ x.__rmul__(y) <==> y*x """
181         pass
182 
183     def __ror__(self, y): # real signature unknown; restored from __doc__
184         """ x.__ror__(y) <==> y|x """
185         pass
186 
187     def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
188         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
189         pass
190 
191     def __rrshift__(self, y): # real signature unknown; restored from __doc__
192         """ x.__rrshift__(y) <==> y>>x """
193         pass
194 
195     def __rshift__(self, y): # real signature unknown; restored from __doc__
196         """ x.__rshift__(y) <==> x>>y """
197         pass
198 
199     def __rsub__(self, y): # real signature unknown; restored from __doc__
200         """ x.__rsub__(y) <==> y-x """
201         pass
202 
203     def __rtruediv__(self, y): # real signature unknown; restored from __doc__
204         """ x.__rtruediv__(y) <==> y/x """
205         pass
206 
207     def __rxor__(self, y): # real signature unknown; restored from __doc__
208         """ x.__rxor__(y) <==> y^x """
209         pass
210 
211     def __sizeof__(self, *args, **kwargs): # real signature unknown
212         """ Returns size in memory, in bytes """
213         pass
214 
215     def __str__(self): # real signature unknown; restored from __doc__
216         """ x.__str__() <==> str(x) """
217         pass
218 
219     def __sub__(self, y): # real signature unknown; restored from __doc__
220         """ x.__sub__(y) <==> x-y """
221         pass
222 
223     def __truediv__(self, y): # real signature unknown; restored from __doc__
224         """ x.__truediv__(y) <==> x/y """
225         pass
226 
227     def __trunc__(self, *args, **kwargs): # real signature unknown
228         """ Truncating an Integral returns itself. """
229         pass
230 
231     def __xor__(self, y): # real signature unknown; restored from __doc__
232         """ x.__xor__(y) <==> x^y """
233         pass
234 
235     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
236     """the denominator of a rational number in lowest terms"""
237 
238     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
239     """the imaginary part of a complex number"""
240 
241     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
242     """the numerator of a rational number in lowest terms"""
243 
244     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
245     """the real part of a complex number"""
long

三、浮点型

如:3.1415926、3.33

每个浮点型都具备如下功能:

  1 class float(object):
  2     """
  3     float(x) -> floating point number
  4     
  5     Convert a string or number to a floating point number, if possible.
  6     """
  7     def as_integer_ratio(self):   
  8         """ 获取改值的最简比 """
  9         """
 10         float.as_integer_ratio() -> (int, int)
 11 
 12         Return a pair of integers, whose ratio is exactly equal to the original
 13         float and with a positive denominator.
 14         Raise OverflowError on infinities and a ValueError on NaNs.
 15 
 16         >>> (10.0).as_integer_ratio()
 17         (10, 1)
 18         >>> (0.0).as_integer_ratio()
 19         (0, 1)
 20         >>> (-.25).as_integer_ratio()
 21         (-1, 4)
 22         """
 23         pass
 24 
 25     def conjugate(self, *args, **kwargs): # real signature unknown
 26         """ Return self, the complex conjugate of any float. """
 27         pass
 28 
 29     def fromhex(self, string):   
 30         """ 将十六进制字符串转换成浮点型 """
 31         """
 32         float.fromhex(string) -> float
 33         
 34         Create a floating-point number from a hexadecimal string.
 35         >>> float.fromhex('0x1.ffffp10')
 36         2047.984375
 37         >>> float.fromhex('-0x1p-1074')
 38         -4.9406564584124654e-324
 39         """
 40         return 0.0
 41 
 42     def hex(self):   
 43         """ 返回当前值的 16 进制表示 """
 44         """
 45         float.hex() -> string
 46         
 47         Return a hexadecimal representation of a floating-point number.
 48         >>> (-0.1).hex()
 49         '-0x1.999999999999ap-4'
 50         >>> 3.14159.hex()
 51         '0x1.921f9f01b866ep+1'
 52         """
 53         return ""
 54 
 55     def is_integer(self, *args, **kwargs): # real signature unknown
 56         """ Return True if the float is an integer. """
 57         pass
 58 
 59     def __abs__(self):   
 60         """ x.__abs__() <==> abs(x) """
 61         pass
 62 
 63     def __add__(self, y):   
 64         """ x.__add__(y) <==> x+y """
 65         pass
 66 
 67     def __coerce__(self, y):   
 68         """ x.__coerce__(y) <==> coerce(x, y) """
 69         pass
 70 
 71     def __divmod__(self, y):   
 72         """ x.__divmod__(y) <==> divmod(x, y) """
 73         pass
 74 
 75     def __div__(self, y):   
 76         """ x.__div__(y) <==> x/y """
 77         pass
 78 
 79     def __eq__(self, y):   
 80         """ x.__eq__(y) <==> x==y """
 81         pass
 82 
 83     def __float__(self):   
 84         """ x.__float__() <==> float(x) """
 85         pass
 86 
 87     def __floordiv__(self, y):   
 88         """ x.__floordiv__(y) <==> x//y """
 89         pass
 90 
 91     def __format__(self, format_spec):   
 92         """
 93         float.__format__(format_spec) -> string
 94         
 95         Formats the float according to format_spec.
 96         """
 97         return ""
 98 
 99     def __getattribute__(self, name):   
100         """ x.__getattribute__('name') <==> x.name """
101         pass
102 
103     def __getformat__(self, typestr):   
104         """
105         float.__getformat__(typestr) -> string
106         
107         You probably don't want to use this function.  It exists mainly to be
108         used in Python's test suite.
109         
110         typestr must be 'double' or 'float'.  This function returns whichever of
111         'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
112         format of floating point numbers used by the C type named by typestr.
113         """
114         return ""
115 
116     def __getnewargs__(self, *args, **kwargs): # real signature unknown
117         pass
118 
119     def __ge__(self, y):   
120         """ x.__ge__(y) <==> x>=y """
121         pass
122 
123     def __gt__(self, y):   
124         """ x.__gt__(y) <==> x>y """
125         pass
126 
127     def __hash__(self):   
128         """ x.__hash__() <==> hash(x) """
129         pass
130 
131     def __init__(self, x):   
132         pass
133 
134     def __int__(self):   
135         """ x.__int__() <==> int(x) """
136         pass
137 
138     def __le__(self, y):   
139         """ x.__le__(y) <==> x<=y """
140         pass
141 
142     def __long__(self):   
143         """ x.__long__() <==> long(x) """
144         pass
145 
146     def __lt__(self, y):   
147         """ x.__lt__(y) <==> x"""
148         pass
149 
150     def __mod__(self, y):   
151         """ x.__mod__(y) <==> x%y """
152         pass
153 
154     def __mul__(self, y):   
155         """ x.__mul__(y) <==> x*y """
156         pass
157 
158     def __neg__(self):   
159         """ x.__neg__() <==> -x """
160         pass
161 
162     @staticmethod # known case of __new__
163     def __new__(S, *more):   
164         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
165         pass
166 
167     def __ne__(self, y):   
168         """ x.__ne__(y) <==> x!=y """
169         pass
170 
171     def __nonzero__(self):   
172         """ x.__nonzero__() <==> x != 0 """
173         pass
174 
175     def __pos__(self):   
176         """ x.__pos__() <==> +x """
177         pass
178 
179     def __pow__(self, y, z=None):   
180         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
181         pass
182 
183     def __radd__(self, y):   
184         """ x.__radd__(y) <==> y+x """
185         pass
186 
187     def __rdivmod__(self, y):   
188         """ x.__rdivmod__(y) <==> divmod(y, x) """
189         pass
190 
191     def __rdiv__(self, y):   
192         """ x.__rdiv__(y) <==> y/x """
193         pass
194 
195     def __repr__(self):   
196         """ x.__repr__() <==> repr(x) """
197         pass
198 
199     def __rfloordiv__(self, y):   
200         """ x.__rfloordiv__(y) <==> y//x """
201         pass
202 
203     def __rmod__(self, y):   
204         """ x.__rmod__(y) <==> y%x """
205         pass
206 
207     def __rmul__(self, y):   
208         """ x.__rmul__(y) <==> y*x """
209         pass
210 
211     def __rpow__(self, x, z=None):   
212         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
213         pass
214 
215     def __rsub__(self, y):   
216         """ x.__rsub__(y) <==> y-x """
217         pass
218 
219     def __rtruediv__(self, y):   
220         """ x.__rtruediv__(y) <==> y/x """
221         pass
222 
223     def __setformat__(self, typestr, fmt):   
224         """
225         float.__setformat__(typestr, fmt) -> None
226         
227         You probably don't want to use this function.  It exists mainly to be
228         used in Python's test suite.
229         
230         typestr must be 'double' or 'float'.  fmt must be one of 'unknown',
231         'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
232         one of the latter two if it appears to match the underlying C reality.
233         
234         Override the automatic determination of C-level floating point type.
235         This affects how floats are converted to and from binary strings.
236         """
237         pass
238 
239     def __str__(self):   
240         """ x.__str__() <==> str(x) """
241         pass
242 
243     def __sub__(self, y):   
244         """ x.__sub__(y) <==> x-y """
245         pass
246 
247     def __truediv__(self, y):   
248         """ x.__truediv__(y) <==> x/y """
249         pass
250 
251     def __trunc__(self, *args, **kwargs): # real signature unknown
252         """ Return the Integral closest to x between 0 and x. """
253         pass
254 
255     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
256     """the imaginary part of a complex number"""
257 
258     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
259     """the real part of a complex number"""
float

四、字符串

如:'ghost','wangwei'

每个字符串都具备如下功能:

  1 class str(basestring):
  2     """
  3     str(object='') -> string
  4     
  5     Return a nice string representation of the object.
  6     If the argument is a string, the return value is the same object.
  7     """
  8     def capitalize(self):  
  9         """ 首字母变大写 
 10         >>> s='hello world'
 11         >>> s.capitalize()
 12         'Hello world'
 13         >>> 
 14         """
 15         """
 16         S.capitalize() -> string
 17         
 18         Return a copy of the string S with only its first character
 19         capitalized.
 20         """
 21         return ""
 22 
 23     def center(self, width, fillchar=None):  
 24         """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 
 25         >>> s.center(20,'-=')
 26         Traceback (most recent call last):
 27           File "", line 1, in 
 28         TypeError: must be char, not str  ==>只能是一个字符,不能是字符串
 29         >>> s.center(20,'=') 
 30         '====hello world====='
 31         >>> 
 32         """
 33         """
 34         S.center(width[, fillchar]) -> string
 35         
 36         Return S centered in a string of length width. Padding is
 37         done using the specified fill character (default is a space)
 38         """
 39         return ""
 40 
 41     def count(self, sub, start=None, end=None):  
 42         """ 子序列个数 计算子序列出现的次数
 43         >>> s
 44         'hello world'
 45         >>> s.count('o')
 46         2
 47         >>> s.count('l')
 48         3
 49         >>> 
 50         """
 51         """
 52         S.count(sub[, start[, end]]) -> int
 53         
 54         Return the number of non-overlapping occurrences of substring sub in
 55         string S[start:end].  Optional arguments start and end are interpreted
 56         as in slice notation.
 57         """
 58         return 0
 59 
 60     def decode(self, encoding=None, errors=None):  
 61         """ 解码 """
 62         """
 63         S.decode([encoding[,errors]]) -> object
 64         
 65         Decodes S using the codec registered for encoding. encoding defaults
 66         to the default encoding. errors may be given to set a different error
 67         handling scheme. Default is 'strict' meaning that encoding errors raise
 68         a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 69         as well as any other name registered with codecs.register_error that is
 70         able to handle UnicodeDecodeErrors.
 71         """
 72         return object()
 73 
 74     def encode(self, encoding=None, errors=None):  
 75         """ 编码,针对unicode """
 76         """
 77         S.encode([encoding[,errors]]) -> object
 78         
 79         Encodes S using the codec registered for encoding. encoding defaults
 80         to the default encoding. errors may be given to set a different error
 81         handling scheme. Default is 'strict' meaning that encoding errors raise
 82         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 83         'xmlcharrefreplace' as well as any other name registered with
 84         codecs.register_error that is able to handle UnicodeEncodeErrors.
 85         """
 86         return object()
 87 
 88     def endswith(self, suffix, start=None, end=None):  
 89         """ 是否以 xxx 结束 
 90         >>> s
 91         'hello world'
 92         >>> s.endswith('d')
 93         True
 94         >>> s.endswith('d',0,4)
 95         False
 96         >>> s.endswith('d',-1) 
 97         True
 98         >>> 
 99         """
100         """
101         S.endswith(suffix[, start[, end]]) -> bool
102         
103         Return True if S ends with the specified suffix, False otherwise.
104         With optional start, test S beginning at that position.
105         With optional end, stop comparing S at that position.
106         suffix can also be a tuple of strings to try.
107         """
108         return False
109 
110     def expandtabs(self, tabsize=None):  
111         """ 将tab转换成空格,默认一个tab转换成8个空格 为了看清效果,使用了14个空格
112         >>> s = 'hello\tworld'
113         >>> print s           
114         hello   world
115         >>> s.expandtabs(14)  
116         'hello         world'
117         >>> 
118         """
119         """
120         S.expandtabs([tabsize]) -> string
121         
122         Return a copy of S where all tab characters are expanded using spaces.
123         If tabsize is not given, a tab size of 8 characters is assumed.
124         """
125         return ""
126 
127     def find(self, sub, start=None, end=None):  
128         """ 寻找子序列位置,如果没找到,返回 -1 
129         >>> s
130         'hello         world'
131         >>> s.find('or')
132         15
133         >>> s.find('lo',0,5)
134         3
135         >>> s.find('lo',5,15)
136         -1
137         >>> 
138         """
139         """
140         S.find(sub [,start [,end]]) -> int
141         
142         Return the lowest index in S where substring sub is found,
143         such that sub is contained within S[start:end].  Optional
144         arguments start and end are interpreted as in slice notation.
145         
146         Return -1 on failure.
147         """
148         return 0
149 
150     def format(*args, **kwargs): # known special case of str.format
151         """ 字符串格式化,动态参数,将函数式编程时细说 """
152         """
153         >>> s = 'hello {0},I am {1}'
154         >>> s.format('Tom','Jerry')
155         'hello Tom,I am Jerry'
156         >>> s = 'hello {a},I am {b}' 
157         >>> s.format(b='Tom',a='Jerry')
158         'hello Jerry,I am Tom'
159         >>> 
160         传入一个列表,列表的元素要和要替换的对上,传入的时候要加一个‘*’
161         >>> s = 'hello {0},I am {1}'   
162         >>> li = ['xiaogou','Tom']
163         >>> s.format(*li)
164         'hello xiaogou,I am Tom'
165         >>> 
166         传入一个字典,列表的中的key要和字符串中的占位符对应上,传入的时候字典名前要加两个‘**’
167         一个‘*’和两个‘*’的意思是动态参数,列表用一个‘*’,字典用两个‘*’。这在函数传参数时也适用
168         >>> s = 'hello {a},I am {b}'   
169         >>> dic = {'a':'Tom','b':'Jerry'}
170         >>> s.format(**dic)
171         'hello Tom,I am Jerry'
172         >>> 
173         """
174         
175         """
176         S.format(*args, **kwargs) -> string
177         
178         Return a formatted version of S, using substitutions from args and kwargs.
179         The substitutions are identified by braces ('{' and '}').
180         """
181         pass
182 
183     def index(self, sub, start=None, end=None):  
184         """ 子序列位置,如果没找到,报错 
185         >>> s.index('lo',0,5)
186         3
187         >>> s.index('lo',5,15)
188         Traceback (most recent call last):
189           File "", line 1, in 
190         ValueError: substring not found
191         >>> 
192         """
193         """
194         S.index(sub [,start [,end]]) -> int
195         
196         Like S.find() but raise ValueError when the substring is not found.
197         """
198         return 0
199 
200     def isalnum(self):  
201         """ 是否是字母和数字 
202         >>> s
203         'hello         world'
204         >>> s.isalnum()
205         False
206         >>> s='helloworld'
207         >>> s.isalnum()   
208         True
209         >>> s='1234'
210         >>> s.isalnum()
211         True
212         >>> 
213         """
214         """
215         S.isalnum() -> bool
216         
217         Return True if all characters in S are alphanumeric
218         and there is at least one character in S, False otherwise.
219         """
220         return False
221 
222     def isalpha(self):  
223         """ 是否是字母 
224         >>> s
225         '1234'
226         >>> s.isalpha()
227         False
228         >>> s='hello'
229         >>> s.isalpha()
230         True
231         >>> 
232         """
233         """
234         S.isalpha() -> bool
235         
236         Return True if all characters in S are alphabetic
237         and there is at least one character in S, False otherwise.
238         """
239         return False
240 
241     def isdigit(self):  
242         """ 是否是数字 
243         >>> s
244         'hello'
245         >>> s.isdigit()
246         False
247         >>> s='1234'
248         >>> s.isdigit()
249         True
250         >>> 
251         """
252         """
253         S.isdigit() -> bool
254         
255         Return True if all characters in S are digits
256         and there is at least one character in S, False otherwise.
257         """
258         return False
259 
260     def islower(self):  
261         """ 是否小写 
262         >>> s
263         '1234'
264         >>> s.islower()
265         False
266         >>> s='heLLo'
267         >>> s.islower()
268         False
269         >>> s='hello'
270         >>> s.islower()
271         True
272         >>> 
273         """
274         """
275         S.islower() -> bool
276         
277         Return True if all cased characters in S are lowercase and there is
278         at least one cased character in S, False otherwise.
279         """
280         return False
281 
282     def isspace(self):  
283         """
284         >>> s='  '
285         >>> s.isspace()
286         True
287         >>> s='hello'
288         >>> s='he llo'
289         >>> s.isspace()
290         False
291         >>> 
292         """
293         """
294         S.isspace() -> bool
295         
296         Return True if all characters in S are whitespace
297         and there is at least one character in S, False otherwise.
298         """
299         return False
300 
301     def istitle(self): 
302         """ 是否是标题,判断依据是单词的首字母为大写
303         >>> s='hello world'
304         >>> s.istitle()
305         False
306         >>> s='Hello World'
307         >>> s.istitle()    
308         True
309         >>> 
310         """
311         """
312         S.istitle() -> bool
313         
314         Return True if S is a titlecased string and there is at least one
315         character in S, i.e. uppercase characters may only follow uncased
316         characters and lowercase characters only cased ones. Return False
317         otherwise.
318         """
319         return False
320 
321     def isupper(self):  
322         """ 是否是大写字母
323         >>> s
324         'Hello World'
325         >>> s.isupper()
326         False
327         >>> s='ABC'
328         >>> s.isupper()
329         True
330         >>> 
331         """
332         """
333         S.isupper() -> bool
334         
335         Return True if all cased characters in S are uppercase and there is
336         at least one cased character in S, False otherwise.
337         """
338         return False
339 
340     def join(self, iterable):  
341         """ 连接 拼接字符串,参数为迭代器,可以用列表,元组,前面的就是分隔符,
342             比如s='ABC'就用ABC连接,如果是空格,就用空格连接
343         >>> li = ['Hello','World']
344         >>> s.join(li)
345         'HelloABCWorld'
346         >>> ''.join(li)
347         'HelloWorld'
348         >>> ' '.join(li)
349         'Hello World'
350         >>> 
351         """
352         """
353         S.join(iterable) -> string
354         
355         Return a string which is the concatenation of the strings in the
356         iterable.  The separator between elements is S.
357         """
358         return ""
359 
360     def ljust(self, width, fillchar=None):  
361         """ 内容左对齐,右侧填充 
362         >>> s
363         'ABC'
364         >>> s.ljust(20)
365         'ABC                 '
366         >>> s.ljust(20,'*')
367         'ABC*****************'
368         >>> 
369         """
370         """
371         S.ljust(width[, fillchar]) -> string
372         
373         Return S left-justified in a string of length width. Padding is
374         done using the specified fill character (default is a space).
375         """
376         return ""
377 
378     def lower(self):  
379         """ 变小写 
380         >>> s
381         'ABC'
382         >>> s.lower()
383         'abc'
384         >>> 
385         """
386         """
387         S.lower() -> string
388         
389         Return a copy of the string S converted to lowercase.
390         """
391         return ""
392 
393     def lstrip(self, chars=None):  
394         """ 移除左侧空白 
395         >>> s = '  ABC  '
396         >>> s.lstrip()
397         'ABC  '
398         >>> 
399         """
400         """
401         S.lstrip([chars]) -> string or unicode
402         
403         Return a copy of the string S with leading whitespace removed.
404         If chars is given and not None, remove characters in chars instead.
405         If chars is unicode, S will be converted to unicode before stripping
406         """
407         return ""
408 
409     def partition(self, sep):  
410         """ 分割,前,中,后三部分 
411         >>> s='abcABCabc'
412         >>> s.partition('ABC')
413         ('abc', 'ABC', 'abc')
414         >>> 
415         """
416         """
417         S.partition(sep) -> (head, sep, tail)
418         
419         Search for the separator sep in S, and return the part before it,
420         the separator itself, and the part after it.  If the separator is not
421         found, return S and two empty strings.
422         """
423         pass
424 
425     def replace(self, old, new, count=None):  
426         """ 替换 
427         >>> s
428         'abcABCabc'
429         >>> s.replace('ABC','DEF')
430         'abcDEFabc'
431         >>> 
432         """
433         """
434         S.replace(old, new[, count]) -> string
435         
436         Return a copy of string S with all occurrences of substring
437         old replaced by new.  If the optional argument count is
438         given, only the first count occurrences are replaced.
439         """
440         return ""
441 
442     def rfind(self, sub, start=None, end=None):  
443         """ 从右侧开始查找 """
444         """
445         S.rfind(sub [,start [,end]]) -> int
446         
447         Return the highest index in S where substring sub is found,
448         such that sub is contained within S[start:end].  Optional
449         arguments start and end are interpreted as in slice notation.
450         
451         Return -1 on failure.
452         """
453         return 0
454 
455     def rindex(self, sub, start=None, end=None):  
456         """ 从右侧开始查找 """
457         """
458         S.rindex(sub [,start [,end]]) -> int
459         
460         Like S.rfind() but raise ValueError when the substring is not found.
461         """
462         return 0
463 
464     def rjust(self, width, fillchar=None):  
465         """ 右对齐 
466         >>> s
467         'abcABCabc'
468         >>> s.rjust(20)
469         '           abcABCabc'
470         >>> 
471         """
472         """
473         S.rjust(width[, fillchar]) -> string
474         
475         Return S right-justified in a string of length width. Padding is
476         done using the specified fill character (default is a space)
477         """
478         return ""
479 
480     def rpartition(self, sep):  
481         """ 从右侧开始分割成三部分 """
482         """
483         S.rpartition(sep) -> (head, sep, tail)
484         
485         Search for the separator sep in S, starting at the end of S, and return
486         the part before it, the separator itself, and the part after it.  If the
487         separator is not found, return two empty strings and S.
488         """
489         pass
490 
491     def rsplit(self, sep=None, maxsplit=None):  
492         """ 从右侧分割成一个列表,分割符不会被当做元素
493         >>> s
494         'abcABCabc'
495         >>> s.rsplit('B')
496         ['abcA', 'Cabc']
497         >>> 
498         """
499         """
500         S.rsplit([sep [,maxsplit]]) -> list of strings
501         
502         Return a list of the words in the string S, using sep as the
503         delimiter string, starting at the end of the string and working
504         to the front.  If maxsplit is given, at most maxsplit splits are
505         done. If sep is not specified or is None, any whitespace string
506         is a separator.
507         """
508         return []
509 
510     def rstrip(self, chars=None):  
511         """ 过滤右边的空格
512         >>> s = '  ABC  '
513         >>> s.rstrip()
514         '  ABC'
515         >>> 
516         """
517         """
518         S.rstrip([chars]) -> string or unicode
519         
520         Return a copy of the string S with trailing whitespace removed.
521         If chars is given and not None, remove characters in chars instead.
522         If chars is unicode, S will be converted to unicode before stripping
523         """
524         return ""
525 
526     def split(self, sep=None, maxsplit=None):  
527         """ 分割, maxsplit最多分割几次 
528         >>> s = 'hello tom i am jerry'
529         >>> s.split()
530         ['hello', 'tom', 'i', 'am', 'jerry']
531         >>> s = 'ghost:hello:123'
532         >>> s.split(':')
533         ['ghost', 'hello', '123']
534         >>> 
535         """
536         """
537         S.split([sep [,maxsplit]]) -> list of strings
538         
539         Return a list of the words in the string S, using sep as the
540         delimiter string.  If maxsplit is given, at most maxsplit
541         splits are done. If sep is not specified or is None, any
542         whitespace string is a separator and empty strings are removed
543         from the result.
544         """
545         return []
546 
547     def splitlines(self, keepends=False):  
548         """ 根据换行分割 
549         >>> s = 'hello\nworld\nwe'
550         >>> s.splitlines()        
551         ['hello', 'world', 'we']
552         >>> 
553         """
554         """
555         S.splitlines(keepends=False) -> list of strings
556         
557         Return a list of the lines in S, breaking at line boundaries.
558         Line breaks are not included in the resulting list unless keepends
559         is given and true.
560         """
561         return []
562 
563     def startswith(self, prefix, start=None, end=None):  
564         """ 是否起始 
565         >>> s = 'hello world'
566         >>> s.startswith('wo',6)
567         True
568         >>> s.startswith('ha')  
569         False
570         >>> s.startswith('h') 
571         True
572         >>> 
573         """
574         """
575         S.startswith(prefix[, start[, end]]) -> bool
576         
577         Return True if S starts with the specified prefix, False otherwise.
578         With optional start, test S beginning at that position.
579         With optional end, stop comparing S at that position.
580         prefix can also be a tuple of strings to try.
581         """
582         return False
583 
584     def strip(self, chars=None):  
585         """ 移除两段空白 
586         >>> s = '  hello  '
587         >>> s.strip()
588         'hello'
589         >>> 
590         """
591         """
592         S.strip([chars]) -> string or unicode
593         
594         Return a copy of the string S with leading and trailing
595         whitespace removed.
596         If chars is given and not None, remove characters in chars instead.
597         If chars is unicode, S will be converted to unicode before stripping
598         """
599         return ""
600 
601     def swapcase(self):  
602         """ 大写变小写,小写变大写 
603         >>> s = 'HeLLo woRLD'
604         >>> s.swapcase()
605         'hEllO WOrld'
606         >>> 
607         """
608         """
609         S.swapcase() -> string
610         
611         Return a copy of the string S with uppercase characters
612         converted to lowercase and vice versa.
613         """
614         return ""
615 
616     def title(self):  
617         """ 设置标题格式
618         >>> s = 'hello world'
619         >>> s.title()
620         'Hello World'
621         >>> 
622         """
623         """
624         S.title() -> string
625         
626         Return a titlecased version of S, i.e. words start with uppercase
627         characters, all remaining cased characters have lowercase.
628         """
629         return ""
630 
631     def translate(self, table, deletechars=None):  
632         """
633         转换,需要先做一个对应表,最后一个表示删除字符集合
634         intab = "aeiou"
635         outtab = "12345"
636         trantab = maketrans(intab, outtab)
637         str = "this is string example....wow!!!"
638         print str.translate(trantab, 'xm')
639         
640         >>> import string
641         >>> intab = 'aeiou'
642         >>> outtab = '12345'
643         >>> trantab = string.maketrans(intab,outtab)
644         >>> str1 = 'this is string example...wow!!!'
645         >>> print str1.translate(trantab,'xm')
646         th3s 3s str3ng 21pl2...w4w!!!
647         >>> 
648         """
649 
650         """
651         S.translate(table [,deletechars]) -> string
652         
653         Return a copy of the string S, where all characters occurring
654         in the optional argument deletechars are removed, and the
655         remaining characters have been mapped through the given
656         translation table, which must be a string of length 256 or None.
657         If the table argument is None, no translation is applied and
658         the operation simply removes the characters in deletechars.
659         """
660         return ""
661 
662     def upper(self):  
663         """ 将小写字母转换为大写字母
664         >>> s = 'hello world'
665         >>> s.upper()
666         'HELLO WORLD'
667         >>> 
668         """
669         """
670         S.upper() -> string
671         
672         Return a copy of the string S converted to uppercase.
673         """
674         return ""
675 
676     def zfill(self, width):  
677         """方法返回指定长度的字符串,原字符串右对齐,前面填充0。
678         和rjust的效果是一样的,只不过just需要指定用‘0’填充
679         >>> s.zfill(20)
680         '000000000hello world'
681         >>> s.rjust(20,'0')
682         '000000000hello world'
683         >>> 
684         """
685         """
686         S.zfill(width) -> string
687         
688         Pad a numeric string S with zeros on the left, to fill a field
689         of the specified width.  The string S is never truncated.
690         """
691         return ""
692 
693     def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
694         pass
695 
696     def _formatter_parser(self, *args, **kwargs): # real signature unknown
697         pass
698 
699     def __add__(self, y):  
700         """ x.__add__(y) <==> x+y """
701         pass
702 
703     def __contains__(self, y):  
704         """ x.__contains__(y) <==> y in x """
705         pass
706 
707     def __eq__(self, y):  
708         """ x.__eq__(y) <==> x==y """
709         pass
710 
711     def __format__(self, format_spec):  
712         """
713         S.__format__(format_spec) -> string
714         
715         Return a formatted version of S as described by format_spec.
716         """
717         return ""
718 
719     def __getattribute__(self, name):  
720         """ x.__getattribute__('name') <==> x.name """
721         pass
722 
723     def __getitem__(self, y):  
724         """ x.__getitem__(y) <==> x[y] """
725         pass
726 
727     def __getnewargs__(self, *args, **kwargs): # real signature unknown
728         pass
729 
730     def __getslice__(self, i, j):  
731         """
732         x.__getslice__(i, j) <==> x[i:j]
733                    
734                    Use of negative indices is not supported.
735         """
736         pass
737 
738     def __ge__(self, y):  
739         """ x.__ge__(y) <==> x>=y """
740         pass
741 
742     def __gt__(self, y):  
743         """ x.__gt__(y) <==> x>y """
744         pass
745 
746     def __hash__(self):  
747         """ x.__hash__() <==> hash(x) """
748         pass
749 
750     def __init__(self, string=''): # known special case of str.__init__
751         """
752         str(object='') -> string
753         
754         Return a nice string representation of the object.
755         If the argument is a string, the return value is the same object.
756         # (copied from class doc)
757         """
758         pass
759 
760     def __len__(self):  
761         """ x.__len__() <==> len(x) """
762         pass
763 
764     def __le__(self, y):  
765         """ x.__le__(y) <==> x<=y """
766         pass
767 
768     def __lt__(self, y):  
769         """ x.__lt__(y) <==> x"""
770         pass
771 
772     def __mod__(self, y):  
773         """ x.__mod__(y) <==> x%y """
774         pass
775 
776     def __mul__(self, n):  
777         """ x.__mul__(n) <==> x*n """
778         pass
779 
780     @staticmethod # known case of __new__
781     def __new__(S, *more):  
782         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
783         pass
784 
785     def __ne__(self, y):  
786         """ x.__ne__(y) <==> x!=y """
787         pass
788 
789     def __repr__(self):  
790         """ x.__repr__() <==> repr(x) """
791         pass
792 
793     def __rmod__(self, y):  
794         """ x.__rmod__(y) <==> y%x """
795         pass
796 
797     def __rmul__(self, n):  
798         """ x.__rmul__(n) <==> n*x """
799         pass
800 
801     def __sizeof__(self):  
802         """ S.__sizeof__() -> size of S in memory, in bytes """
803         pass
804 
805     def __str__(self):  
806         """ x.__str__() <==> str(x) """
807         pass
str

五、列表

如[1,2,3]、['ghost','tom']

每个列表都具备如下功能:

  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         """ 在列表末尾追加一个元素
  8         >>> li 
  9         ['xiaogou', 'Tom']
 10         >>> li.append('laowang')
 11         >>> li
 12         ['xiaogou', 'Tom', 'laowang']
 13         >>> 
 14         """
 15         """ L.append(object) -- append object to end """
 16         pass
 17 
 18     def count(self, value): # real signature unknown; restored from __doc__
 19         """ 计算元素出现的次数
 20         >>> li
 21         ['xiaogou', 'Tom', 'laowang', 'laowang']
 22         >>> li.count('laowang')
 23         2
 24         >>> 
 25         """
 26         """ L.count(value) -> integer -- return number of occurrences of value """
 27         return 0
 28 
 29     def extend(self, iterable): # real signature unknown; restored from __doc__
 30         """ 扩展列表,用另外一个列表的元素扩展此列表,将另外列表的元素追加进来
 31         >>> lie = [1,2,3,4]
 32         >>> li.extend(lie)
 33         >>> li
 34         ['xiaogou', 'Tom', 'laowang', 'laowang', 1, 2, 3, 4]
 35         >>> 
 36         """
 37         """ L.extend(iterable) -- extend list by appending elements from the iterable """
 38         pass
 39 
 40     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 41         """ 返回第一个出现的元素的索引位置
 42         >>> li
 43         ['xiaogou', 'Tom', 'laowang', 'laowang', 1, 2, 3, 4]
 44         >>> li.index('laowang')
 45         2
 46         >>> 
 47         """
 48         """
 49         L.index(value, [start, [stop]]) -> integer -- return first index of value.
 50         Raises ValueError if the value is not present.
 51         """
 52         return 0
 53 
 54     def insert(self, index, p_object): # real signature unknown; restored from __doc__
 55         """ 在指定位置插入元素,当前位置将向后移
 56         >>> li.index('laowang')
 57         2
 58         >>> li.insert(2,'Jerry')
 59         >>> li
 60         ['xiaogou', 'Tom', 'Jerry', 'laowang', 'laowang', 1, 2, 3, 4]
 61         >>> 
 62         """
 63         """ L.insert(index, object) -- insert object before index """
 64         pass
 65 
 66     def pop(self, index=None): # real signature unknown; restored from __doc__
 67         """ 移除列表中的一个元素,并取出来,可以赋值给另一个变量。默认是最后一个,可以传索引值
 68             只接收一个数字类型的值
 69         >>> li
 70         ['xiaogou', 'Tom', 'Jerry', 'laowang', 'laowang', 1, 2, 3, 4]
 71         >>> a = li.pop(3)        
 72         >>> print a
 73         laowang
 74         >>> li
 75         ['xiaogou', 'Tom', 'Jerry', 'laowang', 1, 2, 3, 4]
 76         >>> 
 77         """
 78         """
 79         L.pop([index]) -> item -- remove and return item at index (default last).
 80         Raises IndexError if list is empty or index is out of range.
 81         """
 82         pass
 83 
 84     def remove(self, value): # real signature unknown; restored from __doc__
 85         """ 移除列表中第一次出现的值,并不能取出赋值给其他变量,和pop不一样
 86         >>> li
 87         ['xiaogou', 'Jerry', 'laowang', 1, 2, 3, 4, 'Tom', 'Tom']
 88         >>> a = li.remove('Tom')      
 89         >>> print a
 90         None
 91         >>> li
 92         ['xiaogou', 'Jerry', 'laowang', 1, 2, 3, 4, 'Tom']
 93         >>> 
 94         """
 95         """
 96         L.remove(value) -- remove first occurrence of value.
 97         Raises ValueError if the value is not present.
 98         """
 99         pass
100 
101     def reverse(self): # real signature unknown; restored from __doc__
102         """ 倒序列表
103         >>> li
104         ['xiaogou', 'Jerry', 'laowang', 1, 2, 3, 4, 'Tom']
105         >>> li.reverse()
106         >>> li
107         ['Tom', 4, 3, 2, 1, 'laowang', 'Jerry', 'xiaogou']
108         >>> 
109         """
110         """ L.reverse() -- reverse *IN PLACE* """
111         pass
112 
113     def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
114         """ 给列表排序
115         >>> li
116         ['Tom', 4, 3, 2, 1, 'laowang', 'Jerry', 'xiaogou']
117         >>> li.sort()
118         >>> li
119         [1, 2, 3, 4, 'Jerry', 'Tom', 'laowang', 'xiaogou']
120         >>> 
121         """
122         """
123         L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
124         cmp(x, y) -> -1, 0, 1
125         """
126         pass
127 
128     def __add__(self, y): # real signature unknown; restored from __doc__
129         """ x.__add__(y) <==> x+y """
130         pass
131 
132     def __contains__(self, y): # real signature unknown; restored from __doc__
133         """ x.__contains__(y) <==> y in x """
134         pass
135 
136     def __delitem__(self, y): # real signature unknown; restored from __doc__
137         """ x.__delitem__(y) <==> del x[y] """
138         pass
139 
140     def __delslice__(self, i, j): # real signature unknown; restored from __doc__
141         """
142         x.__delslice__(i, j) <==> del x[i:j]
143                    
144                    Use of negative indices is not supported.
145         """
146         pass
147 
148     def __eq__(self, y): # real signature unknown; restored from __doc__
149         """ x.__eq__(y) <==> x==y """
150         pass
151 
152     def __getattribute__(self, name): # real signature unknown; restored from __doc__
153         """ x.__getattribute__('name') <==> x.name """
154         pass
155 
156     def __getitem__(self, y): # real signature unknown; restored from __doc__
157         """ x.__getitem__(y) <==> x[y] """
158         pass
159 
160     def __getslice__(self, i, j): # real signature unknown; restored from __doc__
161         """
162         x.__getslice__(i, j) <==> x[i:j]
163                    
164                    Use of negative indices is not supported.
165         """
166         pass
167 
168     def __ge__(self, y): # real signature unknown; restored from __doc__
169         """ x.__ge__(y) <==> x>=y """
170         pass
171 
172     def __gt__(self, y): # real signature unknown; restored from __doc__
173         """ x.__gt__(y) <==> x>y """
174         pass
175 
176     def __iadd__(self, y): # real signature unknown; restored from __doc__
177         """ x.__iadd__(y) <==> x+=y """
178         pass
179 
180     def __imul__(self, y): # real signature unknown; restored from __doc__
181         """ x.__imul__(y) <==> x*=y """
182         pass
183 
184     def __init__(self, seq=()): # known special case of list.__init__
185         """
186         list() -> new empty list
187         list(iterable) -> new list initialized from iterable's items
188         # (copied from class doc)
189         """
190         pass
191 
192     def __iter__(self): # real signature unknown; restored from __doc__
193         """ x.__iter__() <==> iter(x) """
194         pass
195 
196     def __len__(self): # real signature unknown; restored from __doc__
197         """ x.__len__() <==> len(x) """
198         pass
199 
200     def __le__(self, y): # real signature unknown; restored from __doc__
201         """ x.__le__(y) <==> x<=y """
202         pass
203 
204     def __lt__(self, y): # real signature unknown; restored from __doc__
205         """ x.__lt__(y) <==> x"""
206         pass
207 
208     def __mul__(self, n): # real signature unknown; restored from __doc__
209         """ x.__mul__(n) <==> x*n """
210         pass
211 
212     @staticmethod # known case of __new__
213     def __new__(S, *more): # real signature unknown; restored from __doc__
214         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
215         pass
216 
217     def __ne__(self, y): # real signature unknown; restored from __doc__
218         """ x.__ne__(y) <==> x!=y """
219         pass
220 
221     def __repr__(self): # real signature unknown; restored from __doc__
222         """ x.__repr__() <==> repr(x) """
223         pass
224 
225     def __reversed__(self): # real signature unknown; restored from __doc__
226         """ L.__reversed__() -- return a reverse iterator over the list """
227         pass
228 
229     def __rmul__(self, n): # real signature unknown; restored from __doc__
230         """ x.__rmul__(n) <==> n*x """
231         pass
232 
233     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
234         """ x.__setitem__(i, y) <==> x[i]=y """
235         pass
236 
237     def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
238         """
239         x.__setslice__(i, j, y) <==> x[i:j]=y
240                    
241                    Use  of negative indices is not supported.
242         """
243         pass
244 
245     def __sizeof__(self): # real signature unknown; restored from __doc__
246         """ L.__sizeof__() -- size of L in memory, in bytes """
247         pass
248 
249     __hash__ = None
list

六、元组

如:(11,22,33)、('Tom','Jerry')

每个元组都具备如下功能:

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

七、字典

如:{'name':'ghost','age':33}、{'host':'127.0.0.1','port':80}

注:循环时,默认循环key

字典在修改内容后不会另外开辟内存空间

列表不可以当做字典的key,因为列表是可变的,元组可以,因为元组是不可变的,但不要这么干,太乱

字符串、数字和类的实例可以当做key

每个字典都具备如下功能

  1 class dict(object):
  2     """
  3     在程序中判断数据类型
  4     >>> type(dic) is dict
  5     True
  6     >>> type(dic) is list
  7     False
  8     >>> 
  9     dict() -> new empty dictionary
 10     dict(mapping) -> new dictionary initialized from a mapping object's
 11         (key, value) pairs
 12     dict(iterable) -> new dictionary initialized as if via:
 13         d = {}
 14         for k, v in iterable:
 15             d[k] = v
 16     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 17         in the keyword argument list.  For example:  dict(one=1, two=2)
 18     """
 19 
 20     def clear(self): # real signature unknown; restored from __doc__
 21         """ 清除内容 
 22         >>> dic.clear()
 23         >>> dic
 24         {}
 25         >>> 
 26         """
 27         """ D.clear() -> None.  Remove all items from D. """
 28         pass
 29 
 30     def copy(self): # real signature unknown; restored from __doc__
 31         """ 浅拷贝 只拷贝第一层
 32         >>> c = {}
 33         >>> for i in range(5):c[i] = []
 34         ... 
 35         >>> c
 36         {0: [], 1: [], 2: [], 3: [], 4: []}
 37         >>> c[1].append({"b":1})
 38         >>> c
 39         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: []}
 40         >>> c[1][0]['b']=2
 41         >>> c
 42         {0: [], 1: [{'b': 2}], 2: [], 3: [], 4: []}
 43         >>> c[1][0]['b']=1
 44         >>> d = c
 45         >>> c['Rain'] = 'test'
 46         >>> c
 47         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 48         >>> d
 49         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 50         >>> e = c.copy()
 51         >>> e
 52         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 53         >>> c.pop("Rain")
 54         'test'
 55         >>> c
 56         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: []}
 57         >>> d
 58         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: []}
 59         >>> e
 60         {0: [], 1: [{'b': 1}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 61         >>> c[1][0]['b']
 62         1
 63         >>> c[1][0]['b'] = 'Ghost'
 64         >>> c
 65         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 66         >>> d
 67         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 68         >>> e
 69         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 70         >>>
 71         如果想真正独立的拷贝,需要用另外一个模块——copy
 72         >>> import copy
 73         >>> f = copy.deepcopy(c)
 74         >>> c #原值
 75         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 76         >>> d #别名
 77         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 78         >>> e #浅拷贝
 79         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 80         >>> f #独立拷贝
 81         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 82         >>> c[1][0]['b'] = 'alex' #修改原始数据
 83         >>> c #已经修改
 84         {0: [], 1: [{'b': 'alex'}], 2: [], 3: [], 4: []}
 85         >>> d #因为是别名,所以也跟着修改
 86         {0: [], 1: [{'b': 'alex'}], 2: [], 3: [], 4: []}
 87         >>> e #因为是浅拷贝,只拷贝第一层,第二层不再拷贝,所以也跟着变
 88         {0: [], 1: [{'b': 'alex'}], 2: [], 3: [], 4: [], 'Rain': 'test'}
 89         >>> f #完全独立的一个字典,所以不会跟着变
 90         {0: [], 1: [{'b': 'Ghost'}], 2: [], 3: [], 4: []}
 91         >>> 
 92         """
 93         """ D.copy() -> a shallow copy of D """
 94         pass
 95 
 96     @staticmethod # known case
 97     def fromkeys(S, v=None): # real signature unknown; restored from __doc__
 98         """
 99         dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
100         v defaults to None.
101         """
102         pass
103 
104     def get(self, k, d=None): # real signature unknown; restored from __doc__
105         """ 根据key获取值,d是默认值 在取值时可以直接用下面的方法,但如果key不存在则抛出异常
106             用get方法不会抛出异常,会返回None,如果不想返回None的话,可以设置默认值
107             如‘Failed’
108         >>> dic = {'k1':1234}
109         >>> dic['k1']
110         1234
111         >>> dic['k2']
112         Traceback (most recent call last):
113           File "", line 1, in 
114         KeyError: 'k2'
115         >>> dic.get('k1')
116         1234
117         >>> dic.get('k2')
118         >>> print dic.get('k2','Failed')
119         Failed
120         >>> 
121         """
122         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
123         pass
124 
125     def has_key(self, k): # real signature unknown; restored from __doc__
126         """ 是否有key 据说在3.0里被抛弃 用 a in dic 这个方法也可以判断"""
127         """ D.has_key(k) -> True if D has a key k, else False """
128         return False
129 
130     def items(self): # real signature unknown; restored from __doc__
131         """ 所有项的列表形式 
132         循环列表不要用下面的方法,因为这种方法在数据量很大的时候
133         会非常耗时,因为它要把字典转换成列表,每个元素都会有下标
134         这个过程会很慢,还会增加内存
135         >>> for k,v in dic.items():print k,v 
136         ... 
137         age 18
138         name ghost
139         >>> 
140         用下面的方法
141         >>> for k in dic:print k,dic[k]
142         ... 
143         age 18
144         name ghost
145         >>> 
146         """
147         """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
148         return []
149 
150     def iteritems(self): # real signature unknown; restored from __doc__
151         """ 项可迭代 """
152         """ D.iteritems() -> an iterator over the (key, value) items of D """
153         pass
154 
155     def iterkeys(self): # real signature unknown; restored from __doc__
156         """ key可迭代 """
157         """ D.iterkeys() -> an iterator over the keys of D """
158         pass
159 
160     def itervalues(self): # real signature unknown; restored from __doc__
161         """ value可迭代 """
162         """ D.itervalues() -> an iterator over the values of D """
163         pass
164 
165     def keys(self): # real signature unknown; restored from __doc__
166         """ 所有的key列表 
167         >>> dic.keys()
168         ['age', 'name']
169         >>> 
170         """
171         """ D.keys() -> list of D's keys """
172         return []
173 
174     def pop(self, k, d=None): # real signature unknown; restored from __doc__
175         """ 获取并在字典中移除 将age的值取出并赋值给a
176         并在字典中删除
177         >>> a = dic.pop('age')
178         >>> print a
179         18
180         >>> dic
181         {'name': 'ghost'}
182         >>>
183         删除还有一种方法,就是del,它是可以删除任何变量的
184         >>> dic['age']=22
185         >>> dic
186         {'age': 22, 'name': 'ghost'}
187         >>> del dic['name']
188         >>> dic
189         {'age': 22}
190         >>> 
191         """
192         """
193         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
194         If key is not found, d is returned if given, otherwise KeyError is raised
195         """
196         pass
197 
198     def popitem(self): # real signature unknown; restored from __doc__
199         """ 获取并在字典中移除 随机获取并在字典中移除"""
200         """
201         D.popitem() -> (k, v), remove and return some (key, value) pair as a
202         2-tuple; but raise KeyError if D is empty.
203         """
204         pass
205 
206     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
207         """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 
208         >>> a = {}
209         >>> b = a.fromkeys(range(10),[])
210         >>> b
211         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
212         >>> b.setdefault(11)
213         >>> b
214         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 11: None}
215         >>> b.setdefault(11,'aa')
216         >>> b
217         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 11: None}
218         >>> b.setdefault(12,'aa')
219         'aa'
220         >>> b
221         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 11: None, 12: 'aa'}
222         >>> 
223         """
224         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
225         pass
226 
227     def update(self, E=None, **F): # known special case of dict.update
228         """ 更新 用a字典去更新b字典,如果a字典中有b字典的值,则用a字典的值去替换b字典中的内容
229         如果没有,则将a字典中的值加到b字典中去
230             {'name':'alex', 'age': 18000}
231             [('name','sbsbsb'),]
232         >>> dic
233         {'age': 22, 'name': 'ghost'}
234         >>> dic[10]='replace'
235         >>> dic
236         {'age': 22, 10: 'replace', 'name': 'ghost'}
237         >>> b
238         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 11: None, 12: 'aa'}
239         >>> b.update(dic)
240         >>> b
241         {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 'age': 22, 11: None, 12: 'aa', 10: 'replace', 'name': 'ghost'}
242         >>>     
243         """
244         """
245         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
246         If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
247         If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
248         In either case, this is followed by: for k in F: D[k] = F[k]
249         """
250         pass
251 
252     def values(self): # real signature unknown; restored from __doc__
253         """ 所有的值 
254         >>> dic.values()
255         [22, 'replace', 'ghost']
256         >>>
257         """
258         """ D.values() -> list of D's values """
259         return []
260 
261     def viewitems(self): # real signature unknown; restored from __doc__
262         """ 所有项,只是将内容保存至view对象中 忘记它"""
263         """ D.viewitems() -> a set-like object providing a view on D's items """
264         pass
265 
266     def viewkeys(self): # real signature unknown; restored from __doc__
267         """ D.viewkeys() -> a set-like object providing a view on D's keys """
268         pass
269 
270     def viewvalues(self): # real signature unknown; restored from __doc__
271         """ D.viewvalues() -> an object providing a view on D's values """
272         pass
273 
274     def __cmp__(self, y): # real signature unknown; restored from __doc__
275         """ x.__cmp__(y) <==> cmp(x,y) """
276         pass
277 
278     def __contains__(self, k): # real signature unknown; restored from __doc__
279         """ D.__contains__(k) -> True if D has a key k, else False """
280         return False
281 
282     def __delitem__(self, y): # real signature unknown; restored from __doc__
283         """ x.__delitem__(y) <==> del x[y] """
284         pass
285 
286     def __eq__(self, y): # real signature unknown; restored from __doc__
287         """ x.__eq__(y) <==> x==y """
288         pass
289 
290     def __getattribute__(self, name): # real signature unknown; restored from __doc__
291         """ x.__getattribute__('name') <==> x.name """
292         pass
293 
294     def __getitem__(self, y): # real signature unknown; restored from __doc__
295         """ x.__getitem__(y) <==> x[y] """
296         pass
297 
298     def __ge__(self, y): # real signature unknown; restored from __doc__
299         """ x.__ge__(y) <==> x>=y """
300         pass
301 
302     def __gt__(self, y): # real signature unknown; restored from __doc__
303         """ x.__gt__(y) <==> x>y """
304         pass
305 
306     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
307         """
308         dict() -> new empty dictionary
309         dict(mapping) -> new dictionary initialized from a mapping object's
310             (key, value) pairs
311         dict(iterable) -> new dictionary initialized as if via:
312             d = {}
313             for k, v in iterable:
314                 d[k] = v
315         dict(**kwargs) -> new dictionary initialized with the name=value pairs
316             in the keyword argument list.  For example:  dict(one=1, two=2)
317         # (copied from class doc)
318         """
319         pass
320 
321     def __iter__(self): # real signature unknown; restored from __doc__
322         """ x.__iter__() <==> iter(x) """
323         pass
324 
325     def __len__(self): # real signature unknown; restored from __doc__
326         """ x.__len__() <==> len(x) """
327         pass
328 
329     def __le__(self, y): # real signature unknown; restored from __doc__
330         """ x.__le__(y) <==> x<=y """
331         pass
332 
333     def __lt__(self, y): # real signature unknown; restored from __doc__
334         """ x.__lt__(y) <==> x"""
335         pass
336 
337     @staticmethod # known case of __new__
338     def __new__(S, *more): # real signature unknown; restored from __doc__
339         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
340         pass
341 
342     def __ne__(self, y): # real signature unknown; restored from __doc__
343         """ x.__ne__(y) <==> x!=y """
344         pass
345 
346     def __repr__(self): # real signature unknown; restored from __doc__
347         """ x.__repr__() <==> repr(x) """
348         pass
349 
350     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
351         """ x.__setitem__(i, y) <==> x[i]=y """
352         pass
353 
354     def __sizeof__(self): # real signature unknown; restored from __doc__
355         """ D.__sizeof__() -> size of D in memory, in bytes """
356         pass
357 
358     __hash__ = None
dict

 八、集合

集合也是一种数据类型(set)

直接的赋值方法

1 >>> x = {1,2,3,4}
2 >>> y = {3,4,5,6}
3 >>> type(x)
4 'set'>
5 >>> type(y)
6 'set'>
7 >>> 

集合是无序的,元素不重复,所以就了有去重的功能

set的一个功能就是去重,如下所示

 1 >>> a = range(5,10)
 2 >>> b = range(7,12)
 3 >>> a
 4 [5, 6, 7, 8, 9]
 5 >>> b
 6 [7, 8, 9, 10, 11]
 7 >>> a.append(7)
 8 >>> a
 9 [5, 6, 7, 8, 9, 7]
10 >>> c = set(a)
11 >>> c
12 set([8, 9, 5, 6, 7])
13 >>> 

还有一个功能就是关系测试

 1 >>> c,d
 2 (set([8, 9, 5, 6, 7]), set([8, 9, 10, 11, 7]))
 3 #交集,取出两个集合相同的内容
 4 >>> c & d
 5 set([8, 9, 7])
 6 #并集,取出两个集合的所有内容,并去重
 7 >>> c | d
 8 set([5, 6, 7, 8, 9, 10, 11])
 9 #对称差集,取出两个集合不同的内容
10 >>> c ^ d
11 set([5, 6, 10, 11])
12 #差集,c里有的,d里没有的
13 >>> c - d
14 set([5, 6])
15 >>> 

set是一个无序且不重复的元素集合

  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         >>> a = {1,2,3}
 11         >>> a.add(4)
 12         >>> a
 13         set([1, 2, 3, 4])
 14         >>> a.add(3)
 15         >>> a
 16         set([1, 2, 3, 4])
 17         >>> 
 18         """
 19         """
 20         Add an element to a set.
 21         
 22         This has no effect if the element is already present.
 23         """
 24         pass
 25 
 26     def clear(self, *args, **kwargs): # real signature unknown
 27         """ 清除集合内所有元素
 28         >>> a
 29         set([1, 2, 3, 4])
 30         >>> a.clear()
 31         >>> a
 32         set([])
 33         >>> 
 34         """
 35         """ Remove all elements from this set. """
 36         pass
 37 
 38     def copy(self, *args, **kwargs): # real signature unknown
 39         """ 浅拷贝
 40         >>> a = {1,2,3}
 41         >>> b = a.copy()
 42         >>> b
 43         set([1, 2, 3])
 44         >>>
 45         """
 46         """ Return a shallow copy of a set. """
 47         pass
 48 
 49     def difference(self, *args, **kwargs): # real signature unknown
 50         """ 也就是求差集 a-b的文字形式,在a中有而b中没有的元素
 51         >>> a,b
 52         (set([1, 2, 3, 5]), set([1, 2, 3]))
 53         >>> a.difference(b)
 54         set([5])
 55         >>> 
 56         """
 57         """
 58         Return the difference of two or more sets as a new set.
 59         
 60         (i.e. all elements that are in this set but not the others.)
 61         """
 62         pass
 63 
 64     def difference_update(self, *args, **kwargs): # real signature unknown
 65         """ 删除当前set中的所有包含在 new set 里的元素 
 66         与difference不同的是它会删除当前set的元素
 67         >>> a,b
 68         (set([1, 2, 3, 4]), set([1, 2, 3]))
 69         >>> a.difference_update(b)
 70         >>> a,b
 71         (set([4]), set([1, 2, 3]))
 72         >>> 
 73         """
 74         """ Remove all elements of another set from this set. """
 75         pass
 76 
 77     def discard(self, *args, **kwargs): # real signature unknown
 78         """ 移除元素 如果存在就移除,如果不存在也不报错
 79         >>> a
 80         set([1, 3, 4])
 81         >>> a.discard(5)
 82         >>> a
 83         set([1, 3, 4])
 84         >>> a.discard(1)
 85         >>> a
 86         set([3, 4])
 87         >>> 
 88         """
 89         """
 90         Remove an element from a set if it is a member.
 91         
 92         If the element is not a member, do nothing.
 93         """
 94         pass
 95 
 96     def intersection(self, *args, **kwargs): # real signature unknown
 97         """ 取交集,新创建一个set a & b的文字方法,该方法不会修改原集合
 98         >>> a,b
 99         (set([3, 4]), set([1, 2, 3]))
100         >>> a.intersection(b)
101         set([3])
102         >>> a,b
103         (set([3, 4]), set([1, 2, 3]))
104         >>> 
105         """
106         """
107         Return the intersection of two or more sets as a new set.
108         
109         (i.e. elements that are common to all of the sets.)
110         """
111         pass
112 
113     def intersection_update(self, *args, **kwargs): # real signature unknown
114         """ 取交集,修改原来set 
115         >>> a,b
116         (set([3, 4]), set([1, 2, 3]))
117         >>> a.intersection_update(b)
118         >>> a,b
119         (set([3]), set([1, 2, 3]))
120         >>> 
121         """
122         """ Update a set with the intersection of itself and another. """
123         pass
124 
125     def isdisjoint(self, *args, **kwargs): # real signature unknown
126         """ 如果没有交集,返回true  
127         >>> a,b,c
128         (set([1, 2, 3, 4, 5]), set([1, 2, 3]), set([8, 9, 7]))
129         >>> a.isdisjoint(b)
130         False
131         >>> a.isdisjoint(c)
132         True
133         >>> 
134         """
135         """ Return True if two sets have a null intersection. """
136         pass
137 
138     def issubset(self, *args, **kwargs): # real signature unknown
139         """ 是否是子集 
140         >>> a,b
141         (set([1, 2, 3, 4, 5]), set([1, 2, 3]))
142         >>> b.issubset(a)
143         True
144         >>> 
145         """
146         """ Report whether another set contains this set. """
147         pass
148 
149     def issuperset(self, *args, **kwargs): # real signature unknown
150         """ 是否是父集 
151         >>> a,b
152         (set([1, 2, 3, 4, 5]), set([1, 2, 3]))
153         >>> a.issuperset(b)
154         True
155         >>> 
156         """
157         """ Report whether this set contains another set. """
158         pass
159 
160     def pop(self, *args, **kwargs): # real signature unknown
161         """ 移除并取得任意一个集合元素,如果为空则抛出异常 
162         >>> c
163         set([8, 9, 7])
164         >>> d = c.pop()
165         >>> d
166         8
167         >>> 
168         """
169         """
170         Remove and return an arbitrary set element.
171         Raises KeyError if the set is empty.
172         """
173         pass
174 
175     def remove(self, *args, **kwargs): # real signature unknown
176         """ 移除一个元素,必须是集合的元素,否则为抛出异常 
177         >>> c
178         set([9, 7])
179         >>> c.remove(9)
180         >>> c
181         set([7])
182         >>> c.remove(8)
183         Traceback (most recent call last):
184           File "", line 1, in 
185         KeyError: 8
186         >>> 
187         """
188         """
189         Remove an element from a set; it must be a member.
190         
191         If the element is not a member, raise a KeyError.
192         """
193         pass
194 
195     def symmetric_difference(self, *args, **kwargs): # real signature unknown
196         """ 差集,创建新对象
197         >>> a,b
198         (set([1, 2, 3, 4, 5]), set([1, 2, 3]))
199         >>> a.symmetric_difference(b)
200         set([4, 5])
201         >>> a,b
202         (set([1, 2, 3, 4, 5]), set([1, 2, 3]))
203         """
204         """
205         Return the symmetric difference of two sets as a new set.
206         
207         (i.e. all elements that are in exactly one of the sets.)
208         """
209         pass
210 
211     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
212         """ 差集,改变原来 
213         >>> a,b
214         (set([1, 2, 3, 4, 5]), set([1, 2, 3]))
215         >>> a.symmetric_difference_update(b)
216         >>> a,b
217         (set([4, 5]), set([1, 2, 3]))
218         >>> 
219         """
220         """ Update a set with the symmetric difference of itself and another. """
221         pass
222 
223     def union(self, *args, **kwargs): # real signature unknown
224         """ 并集 
225         >>> a,b
226         (set([1, 2, 3, 4, 5]), set([8, 4, 5, 6, 7]))
227         >>> a.union(b)
228         set([1, 2, 3, 4, 5, 6, 7, 8])
229         >>> 
230         """
231         """
232         Return the union of sets as a new set.
233         
234         (i.e. all elements that are in either set.)
235         """
236         pass
237 
238     def update(self, *args, **kwargs): # real signature unknown
239         """ 更新 用一个集合或序列更新集合
240         >>> a,b
241         (set([1, 2, 3, 4, 5]), set([8, 4, 5, 6, 7]))
242         >>> a.update(b)
243         >>> a
244         set([1, 2, 3, 4, 5, 6, 7, 8])
245         >>> a
246         set([1, 2, 3, 4, 5, 6, 7, 8])
247         >>> b = [8,9,10]
248         >>> a.update(b)
249         >>> a
250         set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
251         #不可以用数字,但可以用字符串
252         >>> a.update(9)
253         Traceback (most recent call last):
254           File "", line 1, in 
255         TypeError: 'int' object is not iterable
256         >>> a.update('a')
257         >>> a
258         set(['a', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
259         >>> a.update('abb')
260         >>> a
261         set(['a', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'b'])
262         >>>   
263         """
264         """ Update a set with the union of itself and others. """
265         pass
266 
267     def __and__(self, y): # real signature unknown; restored from __doc__
268         """ x.__and__(y) <==> x&y """
269         pass
270 
271     def __cmp__(self, y): # real signature unknown; restored from __doc__
272         """ x.__cmp__(y) <==> cmp(x,y) """
273         pass
274 
275     def __contains__(self, y): # real signature unknown; restored from __doc__
276         """ x.__contains__(y) <==> y in x. """
277         pass
278 
279     def __eq__(self, y): # real signature unknown; restored from __doc__
280         """ x.__eq__(y) <==> x==y """
281         pass
282 
283     def __getattribute__(self, name): # real signature unknown; restored from __doc__
284         """ x.__getattribute__('name') <==> x.name """
285         pass
286 
287     def __ge__(self, y): # real signature unknown; restored from __doc__
288         """ x.__ge__(y) <==> x>=y """
289         pass
290 
291     def __gt__(self, y): # real signature unknown; restored from __doc__
292         """ x.__gt__(y) <==> x>y """
293         pass
294 
295     def __iand__(self, y): # real signature unknown; restored from __doc__
296         """ x.__iand__(y) <==> x&=y """
297         pass
298 
299     def __init__(self, seq=()): # known special case of set.__init__
300         """
301         set() -> new empty set object
302         set(iterable) -> new set object
303         
304         Build an unordered collection of unique elements.
305         # (copied from class doc)
306         """
307         pass
308 
309     def __ior__(self, y): # real signature unknown; restored from __doc__
310         """ x.__ior__(y) <==> x|=y """
311         pass
312 
313     def __isub__(self, y): # real signature unknown; restored from __doc__
314         """ x.__isub__(y) <==> x-=y """
315         pass
316 
317     def __iter__(self): # real signature unknown; restored from __doc__
318         """ x.__iter__() <==> iter(x) """
319         pass
320 
321     def __ixor__(self, y): # real signature unknown; restored from __doc__
322         """ x.__ixor__(y) <==> x^=y """
323         pass
324 
325     def __len__(self): # real signature unknown; restored from __doc__
326         """ x.__len__() <==> len(x) """
327         pass
328 
329     def __le__(self, y): # real signature unknown; restored from __doc__
330         """ x.__le__(y) <==> x<=y """
331         pass
332 
333     def __lt__(self, y): # real signature unknown; restored from __doc__
334         """ x.__lt__(y) <==> x"""
335         pass
336 
337     @staticmethod # known case of __new__
338     def __new__(S, *more): # real signature unknown; restored from __doc__
339         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
340         pass
341 
342     def __ne__(self, y): # real signature unknown; restored from __doc__
343         """ x.__ne__(y) <==> x!=y """
344         pass
345 
346     def __or__(self, y): # real signature unknown; restored from __doc__
347         """ x.__or__(y) <==> x|y """
348         pass
349 
350     def __rand__(self, y): # real signature unknown; restored from __doc__
351         """ x.__rand__(y) <==> y&x """
352         pass
353 
354     def __reduce__(self, *args, **kwargs): # real signature unknown
355         """ Return state information for pickling. """
356         pass
357 
358     def __repr__(self): # real signature unknown; restored from __doc__
359         """ x.__repr__() <==> repr(x) """
360         pass
361 
362     def __ror__(self, y): # real signature unknown; restored from __doc__
363         """ x.__ror__(y) <==> y|x """
364         pass
365 
366     def __rsub__(self, y): # real signature unknown; restored from __doc__
367         """ x.__rsub__(y) <==> y-x """
368         pass
369 
370     def __rxor__(self, y): # real signature unknown; restored from __doc__
371         """ x.__rxor__(y) <==> y^x """
372         pass
373 
374     def __sizeof__(self): # real signature unknown; restored from __doc__
375         """ S.__sizeof__() -> size of S in memory, in bytes """
376         pass
377 
378     def __sub__(self, y): # real signature unknown; restored from __doc__
379         """ x.__sub__(y) <==> x-y """
380         pass
381 
382     def __xor__(self, y): # real signature unknown; restored from __doc__
383         """ x.__xor__(y) <==> x^y """
384         pass
385 
386     __hash__ = None
set

练习:寻找差异

#数据库中原有
old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}

#cmdb新汇报的数据
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
}

要求:找出需要删除的
         需要新建的
         需要更新的

注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就需要更新

理解:1、需要删除的就是旧的里有,新的里没有的;2、需要新建的就是旧的里没有,而新的里有的;3、需要更新的就是旧的里有的,新的里也有的;可以用集合来做:1、可以用旧的字典和新的字典做差集,找出旧的里有的;2、可以用新的字典和旧的字典做差集,找到新的里有的,旧的里没有的;3、旧字典和新字典做交集,找到新的和旧的都有的

 1 >>> old_dict
 2 {'#3': {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, '#2': {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, '#1': {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}}
 3 >>> new_dict
 4 {'#3': {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, '#1': {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800}, '#4': {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80}}
 5 #将字典的key做set的元素
 6 >>> old_set = set(old_dict)
 7 >>> new_set = set(new_dict)
 8 >>> old_set,new_set
 9 (set(['#3', '#2', '#1']), set(['#3', '#1', '#4']))
10 #求旧集合的差集,得到需要删除的
11 >>> old_set.difference(new_set)
12 set(['#2'])
13 #求新集合的差集,得到需要新建的
14 >>> new_set.difference(old_set)
15 set(['#4'])
16 #求交集,得到需要更新的
17 >>> old_set.intersection(new_set)
18 set(['#3', '#1'])
19 >>> 
set练习

 

转载于:https://www.cnblogs.com/wangwei325/p/5088751.html

你可能感兴趣的:(Python学习之路——day02)