码迷,mamicode.com
首页 > 编程语言 > 详细

[python_Day2]

时间:2016-08-13 19:37:54      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

摘要:

对象

对于python来说,一切事物都是对象,对象基于类创建:

 

技术分享

 

注:查看对象相关成员 var,type,dir

基本数据类型和序列

int内部功能

技术分享
  1 class int(object):
  2     """
  3     int(x=0) -> integer
  4     int(x, base=10) -> integer
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is a number, return x.__int__().  For floating point
  8     numbers, this truncates towards zero.
  9     
 10     If x is not a number or if base is given, then x must be a string,
 11     bytes, or bytearray instance representing an integer literal in the
 12     given base.  The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded
 13     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 14     Base 0 means to interpret the base from the string as an integer literal.
 15     >>> int(‘0b100‘, base=0)
 16     4
 17     """
 18     def bit_length(self): # real signature unknown; restored from __doc__
 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         6
 28         """
 29         return 0
 30 
 31     def conjugate(self, *args, **kwargs): # real signature unknown
 32         """ Returns self, the complex conjugate of any int. """
 33         pass
 34 
 35     @classmethod # known case
 36     def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 37         """
 38         int.from_bytes(bytes, byteorder, *, signed=False) -> int
 39         
 40         Return the integer represented by the given array of bytes.
 41         
 42         The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
 43         
 44         The byteorder argument determines the byte order used to represent the
 45         integer.  If byteorder is ‘big‘, the most significant byte is at the
 46         beginning of the byte array.  If byteorder is ‘little‘, the most
 47         significant byte is at the end of the byte array.  To request the native
 48         byte order of the host system, use `sys.byteorder‘ as the byte order value.
 49         
 50         The signed keyword-only argument indicates whether two‘s complement is
 51         used to represent the integer.
 52         """
 53         pass
 54 
 55     def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
 56         """
 57         int.to_bytes(length, byteorder, *, signed=False) -> bytes
 58         
 59         Return an array of bytes representing an integer.
 60         
 61         The integer is represented using length bytes.  An OverflowError is
 62         raised if the integer is not representable with the given number of
 63         bytes.
 64         
 65         The byteorder argument determines the byte order used to represent the
 66         integer.  If byteorder is ‘big‘, the most significant byte is at the
 67         beginning of the byte array.  If byteorder is ‘little‘, the most
 68         significant byte is at the end of the byte array.  To request the native
 69         byte order of the host system, use `sys.byteorder‘ as the byte order value.
 70         
 71         The signed keyword-only argument determines whether two‘s complement is
 72         used to represent the integer.  If signed is False and a negative integer
 73         is given, an OverflowError is raised.
 74         """
 75         pass
 76 
 77     def __abs__(self, *args, **kwargs): # real signature unknown
 78         """ abs(self) """
 79         pass
 80 
 81     def __add__(self, *args, **kwargs): # real signature unknown
 82         """ Return self+value. """
 83         pass
 84 
 85     def __and__(self, *args, **kwargs): # real signature unknown
 86         """ Return self&value. """
 87         pass
 88 
 89     def __bool__(self, *args, **kwargs): # real signature unknown
 90         """ self != 0 """
 91         pass
 92 
 93     def __ceil__(self, *args, **kwargs): # real signature unknown
 94         """ Ceiling of an Integral returns itself. """
 95         pass
 96 
 97     def __divmod__(self, *args, **kwargs): # real signature unknown
 98         #相除,得到商和余数组成的元组
 99         """ Return divmod(self, value). """
100         pass
101 
102     def __eq__(self, *args, **kwargs): # real signature unknown
103         """ Return self==value. """
104         pass
105 
106     def __float__(self, *args, **kwargs): # real signature unknown
107         """ float(self) """
108         pass
109 
110     def __floordiv__(self, *args, **kwargs): # real signature unknown
111         """ Return self//value. """
112         pass
113 
114     def __floor__(self, *args, **kwargs): # real signature unknown
115         """ Flooring an Integral returns itself. """
116         pass
117 
118     def __format__(self, *args, **kwargs): # real signature unknown
119         pass
120 
121     def __getattribute__(self, *args, **kwargs): # real signature unknown
122         """ Return getattr(self, name). """
123         pass
124 
125     def __getnewargs__(self, *args, **kwargs): # real signature unknown
126         pass
127 
128     def __ge__(self, *args, **kwargs): # real signature unknown
129         """ Return self>=value. """
130         pass
131 
132     def __gt__(self, *args, **kwargs): # real signature unknown
133         """ Return self>value. """
134         pass
135 
136     def __hash__(self, *args, **kwargs): # real signature unknown
137         """ Return hash(self). """
138         pass
139 
140     def __index__(self, *args, **kwargs): # real signature unknown
141         """ Return self converted to an integer, if self is suitable for use as an index into a list. """
142         pass
143 
144     def __init__(self, x, base=10): # known special case of int.__init__
145         #构造方法
146         """
147         int(x=0) -> integer
148         int(x, base=10) -> integer
149         
150         Convert a number or string to an integer, or return 0 if no arguments
151         are given.  If x is a number, return x.__int__().  For floating point
152         numbers, this truncates towards zero.
153         
154         If x is not a number or if base is given, then x must be a string,
155         bytes, or bytearray instance representing an integer literal in the
156         given base.  The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded
157         by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
158         Base 0 means to interpret the base from the string as an integer literal.
159         >>> int(‘0b100‘, base=0)
160         4
161         # (copied from class doc)
162         """
163         pass
164 
165     def __int__(self, *args, **kwargs): # real signature unknown
166         """ int(self) """
167         pass
168 
169     def __invert__(self, *args, **kwargs): # real signature unknown
170         """ ~self """
171         pass
172 
173     def __le__(self, *args, **kwargs): # real signature unknown
174         """ Return self<=value. """
175         pass
176 
177     def __lshift__(self, *args, **kwargs): # real signature unknown
178         """ Return self<<value. """
179         pass
180 
181     def __lt__(self, *args, **kwargs): # real signature unknown
182         """ Return self<value. """
183         pass
184 
185     def __mod__(self, *args, **kwargs): # real signature unknown
186         """ Return self%value. """
187         pass
188 
189     def __mul__(self, *args, **kwargs): # real signature unknown
190         """ Return self*value. """
191         pass
192 
193     def __neg__(self, *args, **kwargs): # real signature unknown
194         """ -self """
195         pass
196 
197     @staticmethod # known case of __new__
198     def __new__(*args, **kwargs): # real signature unknown
199         """ Create and return a new object.  See help(type) for accurate signature. """
200         pass
201 
202     def __ne__(self, *args, **kwargs): # real signature unknown
203         """ Return self!=value. """
204         pass
205 
206     def __or__(self, *args, **kwargs): # real signature unknown
207         """ Return self|value. """
208         pass
209 
210     def __pos__(self, *args, **kwargs): # real signature unknown
211         """ +self """
212         pass
213 
214     def __pow__(self, *args, **kwargs): # real signature unknown
215         """ Return pow(self, value, mod). """
216         pass
217 
218     def __radd__(self, *args, **kwargs): # real signature unknown
219         """ Return value+self. """
220         pass
221 
222     def __rand__(self, *args, **kwargs): # real signature unknown
223         """ Return value&self. """
224         pass
225 
226     def __rdivmod__(self, *args, **kwargs): # real signature unknown
227         """ Return divmod(value, self). """
228         pass
229 
230     def __repr__(self, *args, **kwargs): # real signature unknown
231         #转化为解释器可读取的形式
232         """ Return repr(self). """
233         pass
234 
235     def __rfloordiv__(self, *args, **kwargs): # real signature unknown
236         """ Return value//self. """
237         pass
238 
239     def __rlshift__(self, *args, **kwargs): # real signature unknown
240         """ Return value<<self. """
241         pass
242 
243     def __rmod__(self, *args, **kwargs): # real signature unknown
244         """ Return value%self. """
245         pass
246 
247     def __rmul__(self, *args, **kwargs): # real signature unknown
248         """ Return value*self. """
249         pass
250 
251     def __ror__(self, *args, **kwargs): # real signature unknown
252         """ Return value|self. """
253         pass
254 
255     def __round__(self, *args, **kwargs): # real signature unknown
256         """
257         Rounding an Integral returns itself.
258         Rounding with an ndigits argument also returns an integer.
259         """
260         pass
261 
262     def __rpow__(self, *args, **kwargs): # real signature unknown
263         """ Return pow(value, self, mod). """
264         pass
265 
266     def __rrshift__(self, *args, **kwargs): # real signature unknown
267         """ Return value>>self. """
268         pass
269 
270     def __rshift__(self, *args, **kwargs): # real signature unknown
271         """ Return self>>value. """
272         pass
273 
274     def __rsub__(self, *args, **kwargs): # real signature unknown
275         """ Return value-self. """
276         pass
277 
278     def __rtruediv__(self, *args, **kwargs): # real signature unknown
279         """ Return value/self. """
280         pass
281 
282     def __rxor__(self, *args, **kwargs): # real signature unknown
283         """ Return value^self. """
284         pass
285 
286     def __sizeof__(self, *args, **kwargs): # real signature unknown
287         """ Returns size in memory, in bytes """
288         pass
289 
290     def __str__(self, *args, **kwargs): # real signature unknown
291         """ Return str(self). """
292         pass
293 
294     def __sub__(self, *args, **kwargs): # real signature unknown
295         """ Return self-value. """
296         pass
297 
298     def __truediv__(self, *args, **kwargs): # real signature unknown
299         """ Return self/value. """
300         pass
301 
302     def __trunc__(self, *args, **kwargs): # real signature unknown
303         """ Truncating an Integral returns itself. """
304         pass
305 
306     def __xor__(self, *args, **kwargs): # real signature unknown
307         """ Return self^value. """
308         pass
309 
310     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
311     """the denominator of a rational number in lowest terms"""
312 
313     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
314     """the imaginary part of a complex number"""
315 
316     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
317     """the numerator of a rational number in lowest terms"""
318 
319     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
320     """the real part of a complex number"""    
View Code

几个常用的功能:

  1. __divmod__():
    技术分享
    1 all_items = 95
    2 pager = 10
    3 result1 = all_items.__divmod__(10)
    4 #__divmod__()功能常用于页面分页,如上共95个数据,每页10个数据。
    5 result2 = all_items.__rdivmod__(10)
    6 print (result1,result2)
    View Code

     

  2. __init__(),构造方法:
    1 >>> n = 19
    2 >>> n = int(19) #这个过程python自动触发__init__构造方法

     

float内部功能

技术分享
  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): # real signature unknown; restored from __doc__
  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): # real signature unknown; restored from __doc__
 30         """
 31         float.fromhex(string) -> float
 32         
 33         Create a floating-point number from a hexadecimal string.
 34         >>> float.fromhex(‘0x1.ffffp10‘)
 35         2047.984375
 36         >>> float.fromhex(‘-0x1p-1074‘)
 37         -5e-324
 38         """
 39         return 0.0
 40 
 41     def hex(self): # real signature unknown; restored from __doc__
 42         """
 43         float.hex() -> string
 44         
 45         Return a hexadecimal representation of a floating-point number.
 46         >>> (-0.1).hex()
 47         ‘-0x1.999999999999ap-4‘
 48         >>> 3.14159.hex()
 49         ‘0x1.921f9f01b866ep+1‘
 50         """
 51         return ""
 52 
 53     def is_integer(self, *args, **kwargs): # real signature unknown
 54         """ Return True if the float is an integer. """
 55         pass
 56 
 57     def __abs__(self, *args, **kwargs): # real signature unknown
 58         """ abs(self) """
 59         pass
 60 
 61     def __add__(self, *args, **kwargs): # real signature unknown
 62         """ Return self+value. """
 63         pass
 64 
 65     def __bool__(self, *args, **kwargs): # real signature unknown
 66         """ self != 0 """
 67         pass
 68 
 69     def __divmod__(self, *args, **kwargs): # real signature unknown
 70         """ Return divmod(self, value). """
 71         pass
 72 
 73     def __eq__(self, *args, **kwargs): # real signature unknown
 74         """ Return self==value. """
 75         pass
 76 
 77     def __float__(self, *args, **kwargs): # real signature unknown
 78         """ float(self) """
 79         pass
 80 
 81     def __floordiv__(self, *args, **kwargs): # real signature unknown
 82         """ Return self//value. """
 83         pass
 84 
 85     def __format__(self, format_spec): # real signature unknown; restored from __doc__
 86         """
 87         float.__format__(format_spec) -> string
 88         
 89         Formats the float according to format_spec.
 90         """
 91         return ""
 92 
 93     def __getattribute__(self, *args, **kwargs): # real signature unknown
 94         """ Return getattr(self, name). """
 95         pass
 96 
 97     def __getformat__(self, typestr): # real signature unknown; restored from __doc__
 98         """
 99         float.__getformat__(typestr) -> string
100         
101         You probably don‘t want to use this function.  It exists mainly to be
102         used in Python‘s test suite.
103         
104         typestr must be ‘double‘ or ‘float‘.  This function returns whichever of
105         ‘unknown‘, ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘ best describes the
106         format of floating point numbers used by the C type named by typestr.
107         """
108         return ""
109 
110     def __getnewargs__(self, *args, **kwargs): # real signature unknown
111         pass
112 
113     def __ge__(self, *args, **kwargs): # real signature unknown
114         """ Return self>=value. """
115         pass
116 
117     def __gt__(self, *args, **kwargs): # real signature unknown
118         """ Return self>value. """
119         pass
120 
121     def __hash__(self, *args, **kwargs): # real signature unknown
122         """ Return hash(self). """
123         pass
124 
125     def __init__(self, x): # real signature unknown; restored from __doc__
126         pass
127 
128     def __int__(self, *args, **kwargs): # real signature unknown
129         """ int(self) """
130         pass
131 
132     def __le__(self, *args, **kwargs): # real signature unknown
133         """ Return self<=value. """
134         pass
135 
136     def __lt__(self, *args, **kwargs): # real signature unknown
137         """ Return self<value. """
138         pass
139 
140     def __mod__(self, *args, **kwargs): # real signature unknown
141         """ Return self%value. """
142         pass
143 
144     def __mul__(self, *args, **kwargs): # real signature unknown
145         """ Return self*value. """
146         pass
147 
148     def __neg__(self, *args, **kwargs): # real signature unknown
149         """ -self """
150         pass
151 
152     @staticmethod # known case of __new__
153     def __new__(*args, **kwargs): # real signature unknown
154         """ Create and return a new object.  See help(type) for accurate signature. """
155         pass
156 
157     def __ne__(self, *args, **kwargs): # real signature unknown
158         """ Return self!=value. """
159         pass
160 
161     def __pos__(self, *args, **kwargs): # real signature unknown
162         """ +self """
163         pass
164 
165     def __pow__(self, *args, **kwargs): # real signature unknown
166         """ Return pow(self, value, mod). """
167         pass
168 
169     def __radd__(self, *args, **kwargs): # real signature unknown
170         """ Return value+self. """
171         pass
172 
173     def __rdivmod__(self, *args, **kwargs): # real signature unknown
174         """ Return divmod(value, self). """
175         pass
176 
177     def __repr__(self, *args, **kwargs): # real signature unknown
178         """ Return repr(self). """
179         pass
180 
181     def __rfloordiv__(self, *args, **kwargs): # real signature unknown
182         """ Return value//self. """
183         pass
184 
185     def __rmod__(self, *args, **kwargs): # real signature unknown
186         """ Return value%self. """
187         pass
188 
189     def __rmul__(self, *args, **kwargs): # real signature unknown
190         """ Return value*self. """
191         pass
192 
193     def __round__(self, *args, **kwargs): # real signature unknown
194         """
195         Return the Integral closest to x, rounding half toward even.
196         When an argument is passed, work like built-in round(x, ndigits).
197         """
198         pass
199 
200     def __rpow__(self, *args, **kwargs): # real signature unknown
201         """ Return pow(value, self, mod). """
202         pass
203 
204     def __rsub__(self, *args, **kwargs): # real signature unknown
205         """ Return value-self. """
206         pass
207 
208     def __rtruediv__(self, *args, **kwargs): # real signature unknown
209         """ Return value/self. """
210         pass
211 
212     def __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__
213         """
214         float.__setformat__(typestr, fmt) -> None
215         
216         You probably don‘t want to use this function.  It exists mainly to be
217         used in Python‘s test suite.
218         
219         typestr must be ‘double‘ or ‘float‘.  fmt must be one of ‘unknown‘,
220         ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘, and in addition can only be
221         one of the latter two if it appears to match the underlying C reality.
222         
223         Override the automatic determination of C-level floating point type.
224         This affects how floats are converted to and from binary strings.
225         """
226         pass
227 
228     def __str__(self, *args, **kwargs): # real signature unknown
229         """ Return str(self). """
230         pass
231 
232     def __sub__(self, *args, **kwargs): # real signature unknown
233         """ Return self-value. """
234         pass
235 
236     def __truediv__(self, *args, **kwargs): # real signature unknown
237         """ Return self/value. """
238         pass
239 
240     def __trunc__(self, *args, **kwargs): # real signature unknown
241         """ Return the Integral closest to x between 0 and x. """
242         pass
243 
244     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
245     """the imaginary part of a complex number"""
246 
247     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
248     """the real part of a complex number"""
249 
250 
251 
252 class FloatingPointError(ArithmeticError):
253     """ Floating point operation failed. """
254     def __init__(self, *args, **kwargs): # real signature unknown
255         pass
256 
257     @staticmethod # known case of __new__
258     def __new__(*args, **kwargs): # real signature unknown
259         """ Create and return a new object.  See help(type) for accurate signature. """
260         pass
View Code

str内部功能

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

常用的功能代码示例:

技术分享
 1 #   _format__()功能在python3中不能使用
 2 
 3 ‘‘‘
 4 #   capitalize()首字母大写化
 5 name = ‘chenghaoqi is a boy!‘
 6 result = name.capitalize()    #字符串不可修改
 7 print (result)
 8 
 9 
10 #   casefold()小写化
11 name = ‘Teacher iS very tirEd‘
12 result = name.casefold()
13 print(result)
14 
15 
16 #   center()居中
17 name = ‘XS‘
18 result = name.center(21,‘*‘)
19 print(result)
20 
21 
22 #   count()统计字符串内子串出现次数,可指定范围
23 name = ‘Teacher iS very tirEd‘
24 result = name.count(‘r‘,7,18)
25 print(result)
26 
27 
28 #   endswith()判断指定范围字符串是否以某个字符串或子串结尾
29 name = ‘Teacher iS very tirEd‘
30 result = name.endswith(‘d‘)
31 print(result)
32 
33 
34 #   expandtabs()把tab转换成空格,默认一个tab8个空格
35 name = ‘Teacher\tvery‘
36 result = name.expandtabs()
37 print(result)  #未执行成功!!!
38 
39 
40 #   find()定位子串在字符串中第一次出现的位置,无则返回-1
41 #   同index()类似,但index()中无结果则报错,而非返回-1
42 name = ‘Teacher iS very tirEd‘
43 result = name.find(‘r‘,7,20)
44 print(result)
45 
46 
47 #   index()定位子串在字符串中第一次出现的位置,无则报错
48 
49 #   format()字符串格式化
50 name = ‘Teacher iS {0} {1}‘
51 result = name.format(‘very‘,‘tired‘)
52 print(result)
53 
54 name = ‘Teacher iS {name} {status}‘
55 result = name.format(name=‘very‘,status=‘tired‘)
56 print(result)
57 
58 
59 #   join()拼接字符串,将字符串连接起来
60 name = [‘a‘,‘e‘,‘i‘,‘o‘,‘u‘]
61 result = ‘‘.join(name)
62 print(result)
63 
64 
65 #   ljust()居左,类似于center(),rjust()
66 name = ‘XS‘
67 result = name.ljust(21,‘*‘)
68 print(result)
69 
70 #   partition()分割,前中后三部分
71 name = ‘Teacher iS very tirEd‘
72 result = name.partition(‘very‘)
73 print(result)
74 
75 #   replace()替换
76 name = ‘Teacher iS very tirEd‘
77 result = name.replace(‘very‘,‘no‘)
78 print(result)
79 
80 #split()分割,默认以空格为分割符
81 name = ‘Teacher iS very tirEd‘
82 result = name.split()
83 result = name.split(‘r‘,2)
84 
85 #strip() 可以去掉字符串两边的字符,默认为空格
86 name = ‘   Teacher iS very tirEd   ‘
87 result = name.split()
88 print(result)
89 name = ‘Teacher iS very tirEd‘
90 name.strip(‘T‘)
91 print(result)
92 
93 #   swapcase()大写变小写,小写变大写
94 
95 name = ‘Teacher iS very tirEd‘
96 result = name.swapcase()
97 print(result)
98 
99 ‘‘‘
View Code

list内部功能

如:

1 >>> lst = list([123,456,789,kkk])
2 >>> lst
3 [123, 456, 789, kkk]

 

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

常用的功能代码示例:

技术分享
 1 >>> lst = list([123,456,789])
 2 >>> lst.append(jack)
 3 >>> lst
 4 [123, 456, 789, jack]
 5 >>> lst.extend([0,tom])
 6 >>> lst
 7 [123, 456, 789, jack, 0, tom]
 8 >>> lst.insert(2,gg)
 9 >>> lst
10 [123, 456, gg, 789, jack, 0, tom]
11 >>> lst.count(gg)
12 1
13 >>> lst.pop()
14 tom
15 >>> lst
16 [123, 456, gg, 789, jack, 0]
17 >>> lst.pop(1)
18 456
19 >>> lst
20 [123, gg, 789, jack, 0]
21 >>> lst.remove(gg)
22 >>> lst.remove(jack)
23 >>> lst
24 [123, 789, 0]
25 >>> lst.sort()
26 >>> lst
27 [0, 123, 789]
28 >>> lst.sort(reverse = True)
29 >>> lst
30 [789, 123, 0]
31 >>> lst.reverse()
32 >>> lst
33 [0, 123, 789]
View Code

tuple内部功能

如:

1 >>> tup = tuple((222,333,444,ggg))
2 >>> tup
3 (222, 333, 444, ggg)

 

元组tuple与列表list的最大的区别在于,元组不可修改,而列表是可以修改的。所以元组的内部功能较少。

技术分享
 1 class tuple(object):
 2     """
 3     tuple() -> empty tuple
 4     tuple(iterable) -> tuple initialized from iterable‘s items
 5     
 6     If the argument is a tuple, the return value is the same object.
 7     """
 8     def count(self, value): # real signature unknown; restored from __doc__
 9         """ T.count(value) -> integer -- return number of occurrences of value """
10         return 0
11 
12     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
13         """
14         T.index(value, [start, [stop]]) -> integer -- return first index of value.
15         Raises ValueError if the value is not present.
16         """
17         return 0
View Code

注:

技术分享

dict内部功能

字典是一种无序的序列。

特点:

  1. 字典的值可以是任意数据类型,包括字符串、整数、对象,甚至字典;
  2. 不允许同一个键重复出现,如果同一个键被赋值两次,后一个值会覆盖前面的值;
  3. 键必须不可变,只能由数、字符串或元组充当,不能用列表。

如:

1 >>> dct = dict({k1:jack,k2:12,k3:male})
2 >>> dct
3 {k2: 12, k1: jack, k3: male}
技术分享
  1 class dict(object):
  2     """
  3     dict() -> new empty dictionary
  4     dict(mapping) -> new dictionary initialized from a mapping object‘s
  5         (key, value) pairs
  6     dict(iterable) -> new dictionary initialized as if via:
  7         d = {}
  8         for k, v in iterable:
  9             d[k] = v
 10     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 11         in the keyword argument list.  For example:  dict(one=1, two=2)
 12     """
 13     def clear(self): # real signature unknown; restored from __doc__
 14         """ D.clear() -> None.  Remove all items from D. """
 15         pass
 16 
 17     def copy(self): # real signature unknown; restored from __doc__
 18         #浅拷贝
 19         """ D.copy() -> a shallow copy of D """
 20         pass
 21 
 22     @staticmethod # known case
 23     def fromkeys(*args, **kwargs): # real signature unknown
 24         """ Returns a new dict with keys from iterable and values equal to value. """
 25         pass
 26 
 27     def get(self, k, d=None): # real signature unknown; restored from __doc__
 28         #根据key获取value
 29         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
 30         pass
 31 
 32     def items(self): # real signature unknown; restored from __doc__
 33         #返回一个有(key,value)组成的元组
 34         """ D.items() -> a set-like object providing a view on D‘s items """
 35         pass
 36 
 37     def keys(self): # real signature unknown; restored from __doc__
 38         #返回一个包含所有key的列表
 39         """ D.keys() -> a set-like object providing a view on D‘s keys """
 40         pass
 41 
 42     def pop(self, k, d=None): # real signature unknown; restored from __doc__
 43         #弹出一个关键字key,并返回它的值value
 44         """
 45         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 46         If key is not found, d is returned if given, otherwise KeyError is raised
 47         """
 48         pass
 49 
 50     def popitem(self): # real signature unknown; restored from __doc__
 51         """
 52         D.popitem() -> (k, v), remove and return some (key, value) pair as a
 53         2-tuple; but raise KeyError if D is empty.
 54         """
 55         pass
 56 
 57     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
 58         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
 59         pass
 60 
 61     def update(self, E=None, **F): # known special case of dict.update
 62         """
 63         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 64         If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 65         If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 66         In either case, this is followed by: for k in F:  D[k] = F[k]
 67         """
 68         pass
 69 
 70     def values(self): # real signature unknown; restored from __doc__
 71         #返回一个包含所有value的列表
 72         """ D.values() -> an object providing a view on D‘s values """
 73         pass
 74 
 75     def __contains__(self, *args, **kwargs): # real signature unknown
 76         """ True if D has a key k, else False. """
 77         pass
 78 
 79     def __delitem__(self, *args, **kwargs): # real signature unknown
 80         """ Delete self[key]. """
 81         pass
 82 
 83     def __eq__(self, *args, **kwargs): # real signature unknown
 84         """ Return self==value. """
 85         pass
 86 
 87     def __getattribute__(self, *args, **kwargs): # real signature unknown
 88         """ Return getattr(self, name). """
 89         pass
 90 
 91     def __getitem__(self, y): # real signature unknown; restored from __doc__
 92         """ x.__getitem__(y) <==> x[y] """
 93         pass
 94 
 95     def __ge__(self, *args, **kwargs): # real signature unknown
 96         """ Return self>=value. """
 97         pass
 98 
 99     def __gt__(self, *args, **kwargs): # real signature unknown
100         """ Return self>value. """
101         pass
102 
103     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
104         """
105         dict() -> new empty dictionary
106         dict(mapping) -> new dictionary initialized from a mapping object‘s
107             (key, value) pairs
108         dict(iterable) -> new dictionary initialized as if via:
109             d = {}
110             for k, v in iterable:
111                 d[k] = v
112         dict(**kwargs) -> new dictionary initialized with the name=value pairs
113             in the keyword argument list.  For example:  dict(one=1, two=2)
114         # (copied from class doc)
115         """
116         pass
117 
118     def __iter__(self, *args, **kwargs): # real signature unknown
119         """ Implement iter(self). """
120         pass
121 
122     def __len__(self, *args, **kwargs): # real signature unknown
123         """ Return len(self). """
124         pass
125 
126     def __le__(self, *args, **kwargs): # real signature unknown
127         """ Return self<=value. """
128         pass
129 
130     def __lt__(self, *args, **kwargs): # real signature unknown
131         """ Return self<value. """
132         pass
133 
134     @staticmethod # known case of __new__
135     def __new__(*args, **kwargs): # real signature unknown
136         """ Create and return a new object.  See help(type) for accurate signature. """
137         pass
138 
139     def __ne__(self, *args, **kwargs): # real signature unknown
140         """ Return self!=value. """
141         pass
142 
143     def __repr__(self, *args, **kwargs): # real signature unknown
144         """ Return repr(self). """
145         pass
146 
147     def __setitem__(self, *args, **kwargs): # real signature unknown
148         """ Set self[key] to value. """
149         pass
150 
151     def __sizeof__(self): # real signature unknown; restored from __doc__
152         """ D.__sizeof__() -> size of D in memory, in bytes """
153         pass
154 
155     __hash__ = None            
View Code

 常用的功能代码示例:

技术分享
 1 >>> dct = dict({k1:jack,k2:12,k3:male})
 2 >>> dct
 3 {k2: 12, k1: jack, k3: male}
 4 >>> dct.clear()
 5 >>> dct
 6 {}
 7 >>> dct = dict({k1:jack,k2:12,k3:male})
 8 >>> dct.get(k2)
 9 12
10 >>> dct.items()
11 dict_items([(k2, 12), (k1, jack), (k3, male)])
12 >>> dct.keys()
13 dict_keys([k2, k1, k3])
14 >>> dct.values()
15 dict_values([12, jack, male])
16 >>> dct.pop(k3)
17 male
18 >>> dct.popitem()
19 (k2, 12)
20 >>> dct
21 {k1: jack}
22 >>> dct[k2] = 12
23 >>> dct
24 {k2: 12, k1: jack}
25 >>> len(dct)
26 2
View Code

 set内部功能

集合set()是一个无序且不重合的元素(‘键‘,key)集合,类似于字典,但是没有’值‘,value。

如:

 1 >>> x = set([a,b,c])
 2 >>> x
 3 {b, c, a}
 4 >>> type(x)
 5 <class set>
 6 >>> y = {aa,bb,cc}
 7 >>> y
 8 {aa, cc, bb}
 9 >>> type(y)
10 <class 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         """
 11         Add an element to a set.
 12         
 13         This has no effect if the element is already present.
 14         """
 15         pass
 16 
 17     def clear(self, *args, **kwargs): # real signature unknown
 18         """ Remove all elements from this set. """
 19         pass
 20 
 21     def copy(self, *args, **kwargs): # real signature unknown
 22         """ Return a shallow copy of a set. """
 23         pass
 24 
 25     def difference(self, *args, **kwargs): # real signature unknown
 26         #求差集,返回的是old set中的差值元素
 27         """
 28         Return the difference of two or more sets as a new set.
 29         
 30         (i.e. all elements that are in this set but not the others.)
 31         """
 32         pass
 33 
 34     def difference_update(self, *args, **kwargs): # real signature unknown
 35         #删除当前set中的所有包含在 new set 里的元素
 36         """ Remove all elements of another set from this set. """
 37         pass
 38 
 39     def discard(self, *args, **kwargs): # real signature unknown
 40         """
 41         Remove an element from a set if it is a member.
 42         
 43         If the element is not a member, do nothing.
 44         """
 45         pass
 46 
 47     def intersection(self, *args, **kwargs): # real signature unknown
 48         #取交集,新创建一个set 
 49         """
 50         Return the intersection of two sets as a new set.
 51         
 52         (i.e. all elements that are in both sets.)
 53         """
 54         pass
 55 
 56     def intersection_update(self, *args, **kwargs): # real signature unknown
 57         #取交集,修改原来set
 58         """ Update a set with the intersection of itself and another. """
 59         pass
 60 
 61     def isdisjoint(self, *args, **kwargs): # real signature unknown
 62         """ Return True if two sets have a null intersection. """
 63         pass
 64 
 65     def issubset(self, *args, **kwargs): # real signature unknown
 66         """ Report whether another set contains this set. """
 67         pass
 68 
 69     def issuperset(self, *args, **kwargs): # real signature unknown
 70         """ Report whether this set contains another set. """
 71         pass
 72 
 73     def pop(self, *args, **kwargs): # real signature unknown
 74         """
 75         Remove and return an arbitrary set element.
 76         Raises KeyError if the set is empty.
 77         """
 78         pass
 79 
 80     def remove(self, *args, **kwargs): # real signature unknown
 81         """
 82         Remove an element from a set; it must be a member.
 83         
 84         If the element is not a member, raise a KeyError.
 85         """
 86         pass
 87 
 88     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 89         #对称差集,也就是两边差值元素都会取到,创建新对象
 90         """
 91         Return the symmetric difference of two sets as a new set.
 92         
 93         (i.e. all elements that are in exactly one of the sets.)
 94         """
 95         pass
 96 
 97     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
 98         #对称差集,也就是两边差值元素都会取到,但只是改变原来对象
 99         """ Update a set with the symmetric difference of itself and another. """
100         pass
101 
102     def union(self, *args, **kwargs): # real signature unknown
103         #并集
104         """
105         Return the union of sets as a new set.
106         
107         (i.e. all elements that are in either set.)
108         """
109         pass
110 
111     def update(self, *args, **kwargs): # real signature unknown
112         """ Update a set with the union of itself and others. """
113         pass   
View Code

常见功能代码示例:

技术分享
 1 >>> x = {a,b,c,d}
 2 >>> y = {a,c,11,22}
 3 >>> x.difference_update(y)
 4 >>> x
 5 {d, b}
 6 >>> x = {a,b,c,d}
 7 >>> y = {a,c,11,22}
 8 >>> z = x.intersection(y)
 9 >>> z
10 {c, a}
11 >>> x.intersection_update(y)
12 >>> x
13 {c, a}
14 >>> x = {a,b,c,d}
15 >>> y = {a,c,11,22}
16 >>> z = x.symmetric_difference(y)
17 >>> z
18 {11, b, 22, d}
19 >>> x.symmetric_difference_update(y)
20 >>> x
21 {d, 22, 11, b}
View Code

下面是一个集合set()实际应用的例子:

技术分享
 1 # 数据库中原有
 2 old_dict = {
 3     "#1": {hostname: c1, cpu_count: 2, mem_capicity: 80},
 4     "#2": {hostname: c1, cpu_count: 2, mem_capicity: 80},
 5     "#3": {hostname: c1, cpu_count: 2, mem_capicity: 80}
 6 }
 7 
 8 # cmdb 新汇报的数据
 9 new_dict = {
10     "#1": {hostname: c1, cpu_count: 2, mem_capicity: 800},
11     "#3": {hostname: c1, cpu_count: 2, mem_capicity: 80},
12     "#4": {hostname: c2, cpu_count: 2, mem_capicity: 80}
13 }
14 
15 ‘‘‘
16 需要删除:?
17 需要新建:?
18 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
19 
20 ‘‘‘
21 
22 # 根据key值来判断;
23 # old,new两者交集,表示这部分内容需要保持不变,或者更新
24 # old,new两者差集,表示这部分old内容需要删除
25 # 注意!这里不用symmetric_difference()方法,而用difference()方法
26 # new,old两者差集,表示需要添加这部分new内容
27 
28 
29 old_keylst = old_dict.keys()
30 new_keylst = new_dict.keys()
31 
32 old_keyset = set(old_keylst)
33 new_keyset = set(new_keylst)
34 
35 need_update_or_reserve = old_keyset.intersection(new_keyset)
36 need_del = old_keyset.difference(new_keyset)
37 need_add = new_keyset.difference(old_keyset)
38 
39 print(need update or reserve:%s\nneed delete:%s\nneed add:%s%(need_update_or_reserve,need_del,need_add))
View Code

 

 

collections模块

计数器Counter

计数器Counter是对字典的补充,继承了字典的类。除了计数器Counter自己的内部功能外,也能使用字典的内部功能。

如:

1 >>> import collections
2 >>> obj = collections.Counter(dasdasdasfsafassadas)
3 >>> print(obj)
4 Counter({a: 7, s: 7, d: 4, f: 2})

计数器Couter内部功能:

技术分享
  1 class Counter(dict):
  2     ‘‘‘Dict subclass for counting hashable items.  Sometimes called a bag
  3     or multiset.  Elements are stored as dictionary keys and their counts
  4     are stored as dictionary values.
  5 
  6     >>> c = Counter(‘abcdeabcdabcaba‘)  # count elements from a string
  7 
  8     >>> c.most_common(3)                # three most common elements
  9     [(‘a‘, 5), (‘b‘, 4), (‘c‘, 3)]
 10     >>> sorted(c)                       # list all unique elements
 11     [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]
 12     >>> ‘‘.join(sorted(c.elements()))   # list elements with repetitions
 13     ‘aaaaabbbbcccdde‘
 14     >>> sum(c.values())                 # total of all counts
 15     15
 16 
 17     >>> c[‘a‘]                          # count of letter ‘a‘
 18     5
 19     >>> for elem in ‘shazam‘:           # update counts from an iterable
 20     ...     c[elem] += 1                # by adding 1 to each element‘s count
 21     >>> c[‘a‘]                          # now there are seven ‘a‘
 22     7
 23     >>> del c[‘b‘]                      # remove all ‘b‘
 24     >>> c[‘b‘]                          # now there are zero ‘b‘
 25     0
 26 
 27     >>> d = Counter(‘simsalabim‘)       # make another counter
 28     >>> c.update(d)                     # add in the second counter
 29     >>> c[‘a‘]                          # now there are nine ‘a‘
 30     9
 31 
 32     >>> c.clear()                       # empty the counter
 33     >>> c
 34     Counter()
 35 
 36     Note:  If a count is set to zero or reduced to zero, it will remain
 37     in the counter until the entry is deleted or the counter is cleared:
 38 
 39     >>> c = Counter(‘aaabbc‘)
 40     >>> c[‘b‘] -= 2                     # reduce the count of ‘b‘ by two
 41     >>> c.most_common()                 # ‘b‘ is still in, but its count is zero
 42     [(‘a‘, 3), (‘c‘, 1), (‘b‘, 0)]
 43 
 44     ‘‘‘
 45     # References:
 46     #   http://en.wikipedia.org/wiki/Multiset
 47     #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
 48     #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
 49     #   http://code.activestate.com/recipes/259174/
 50     #   Knuth, TAOCP Vol. II section 4.6.3
 51 
 52     def __init__(*args, **kwds):
 53         ‘‘‘Create a new, empty Counter object.  And if given, count elements
 54         from an input iterable.  Or, initialize the count from another mapping
 55         of elements to their counts.
 56 
 57         >>> c = Counter()                           # a new, empty counter
 58         >>> c = Counter(‘gallahad‘)                 # a new counter from an iterable
 59         >>> c = Counter({‘a‘: 4, ‘b‘: 2})           # a new counter from a mapping
 60         >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
 61 
 62         ‘‘‘
 63         if not args:
 64             raise TypeError("descriptor ‘__init__‘ of ‘Counter‘ object "
 65                             "needs an argument")
 66         self, *args = args
 67         if len(args) > 1:
 68             raise TypeError(expected at most 1 arguments, got %d % len(args))
 69         super(Counter, self).__init__()
 70         self.update(*args, **kwds)
 71 
 72     def __missing__(self, key):
 73         The count of elements not in the Counter is zero.
 74         # Needed so that self[missing_item] does not raise KeyError
 75         return 0
 76 
 77     def most_common(self, n=None):
 78         #返回计数次数较多的n组元素(key,count_value)组成的列表
 79         ‘‘‘List the n most common elements and their counts from the most
 80         common to the least.  If n is None, then list all element counts.
 81 
 82         >>> Counter(‘abcdeabcdabcaba‘).most_common(3)
 83         [(‘a‘, 5), (‘b‘, 4), (‘c‘, 3)]
 84 
 85         ‘‘‘
 86         # Emulate Bag.sortedByCount from Smalltalk
 87         if n is None:
 88             return sorted(self.items(), key=_itemgetter(1), reverse=True)
 89         return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
 90 
 91     def elements(self):
 92         #计数器中的所有元素,列表形式
 93         #注:此处非所有元素集合,而是包含所有元素集合的迭代器 
 94         ‘‘‘Iterator over elements repeating each as many times as its count.
 95 
 96         >>> c = Counter(‘ABCABC‘)
 97         >>> sorted(c.elements())
 98         [‘A‘, ‘A‘, ‘B‘, ‘B‘, ‘C‘, ‘C‘]
 99 
100         # Knuth‘s example for prime factors of 1836:  2**2 * 3**3 * 17**1
101         >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
102         >>> product = 1
103         >>> for factor in prime_factors.elements():     # loop over factors
104         ...     product *= factor                       # and multiply them
105         >>> product
106         1836
107 
108         Note, if an element‘s count has been set to zero or is a negative
109         number, elements() will ignore it.
110 
111         ‘‘‘
112         # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
113         return _chain.from_iterable(_starmap(_repeat, self.items()))
114 
115     # Override dict methods where necessary
116 
117     @classmethod
118     def fromkeys(cls, iterable, v=None):
119         # There is no equivalent method for counters because setting v=1
120         # means that no element can have a count greater than one.
121         raise NotImplementedError(
122             Counter.fromkeys() is undefined.  Use Counter(iterable) instead.)
123 
124     def update(*args, **kwds):
125         #更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一
126         ‘‘‘Like dict.update() but add counts instead of replacing them.
127 
128         Source can be an iterable, a dictionary, or another Counter instance.
129 
130         >>> c = Counter(‘which‘)
131         >>> c.update(‘witch‘)           # add elements from another iterable
132         >>> d = Counter(‘watch‘)
133         >>> c.update(d)                 # add elements from another counter
134         >>> c[‘h‘]                      # four ‘h‘ in which, witch, and watch
135         4
136 
137         ‘‘‘
138         # The regular dict.update() operation makes no sense here because the
139         # replace behavior results in the some of original untouched counts
140         # being mixed-in with all of the other counts for a mismash that
141         # doesn‘t have a straight-forward interpretation in most counting
142         # contexts.  Instead, we implement straight-addition.  Both the inputs
143         # and outputs are allowed to contain zero and negative counts.
144 
145         if not args:
146             raise TypeError("descriptor ‘update‘ of ‘Counter‘ object "
147                             "needs an argument")
148         self, *args = args
149         if len(args) > 1:
150             raise TypeError(expected at most 1 arguments, got %d % len(args))
151         iterable = args[0] if args else None
152         if iterable is not None:
153             if isinstance(iterable, Mapping):
154                 if self:
155                     self_get = self.get
156                     for elem, count in iterable.items():
157                         self[elem] = count + self_get(elem, 0)
158                 else:
159                     super(Counter, self).update(iterable) # fast path when counter is empty
160             else:
161                 _count_elements(self, iterable)
162         if kwds:
163             self.update(kwds)
164 
165     def subtract(*args, **kwds):
166         #相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量
167         ‘‘‘Like dict.update() but subtracts counts instead of replacing them.
168         Counts can be reduced below zero.  Both the inputs and outputs are
169         allowed to contain zero and negative counts.
170 
171         Source can be an iterable, a dictionary, or another Counter instance.
172 
173         >>> c = Counter(‘which‘)
174         >>> c.subtract(‘witch‘)             # subtract elements from another iterable
175         >>> c.subtract(Counter(‘watch‘))    # subtract elements from another counter
176         >>> c[‘h‘]                          # 2 in which, minus 1 in witch, minus 1 in watch
177         0
178         >>> c[‘w‘]                          # 1 in which, minus 1 in witch, minus 1 in watch
179         -1
180 
181         ‘‘‘
182         if not args:
183             raise TypeError("descriptor ‘subtract‘ of ‘Counter‘ object "
184                             "needs an argument")
185         self, *args = args
186         if len(args) > 1:
187             raise TypeError(expected at most 1 arguments, got %d % len(args))
188         iterable = args[0] if args else None
189         if iterable is not None:
190             self_get = self.get
191             if isinstance(iterable, Mapping):
192                 for elem, count in iterable.items():
193                     self[elem] = self_get(elem, 0) - count
194             else:
195                 for elem in iterable:
196                     self[elem] = self_get(elem, 0) - 1
197         if kwds:
198             self.subtract(kwds)
199 
200     def copy(self):
201         Return a shallow copy.
202         return self.__class__(self)            
View Code

常用功能示例代码:

技术分享
 1 import collections
 2 
 3 #   Counter计数器:
 4 
 5 # x = collections.Counter(‘aabbdfkasd‘)
 6 x = collections.Counter([11,22,33,44,11,33,11])
 7 print(x)
 8 
 9 
10 ‘‘‘
11 y = x.most_common(4)
12 print(y)
13 
14 for i in x.elements():
15     print(i)
16 
17 #Counter继承了字典的类,字典的功能Counter也能用
18 for key,values in x.items():
19     print(key,values)
20 
21 
22 #添加和删除
23 # x.update([11,11,22,‘flexion‘])
24 # x.subtract([11,11,22,‘flexion‘])
25 
26 print(x)
27 ‘‘‘
View Code

有序字典OrderDict

字典dict是无序的序列,而列表list是有序的序列,两者结合就形成了有序字典OrderDict,类似于:

1 for key in list:
2     print( dict[ key ] )

有序字典OrderDict是对字典dict类型的补充,他记住了字典元素添加的顺序。有序字典OrderDict的功能很多与字典dict相似:

技术分享
  1 class OrderedDict(dict):
  2     Dictionary that remembers insertion order
  3     # An inherited dict maps keys to values.
  4     # The inherited dict provides __getitem__, __len__, __contains__, and get.
  5     # The remaining methods are order-aware.
  6     # Big-O running times for all methods are the same as regular dictionaries.
  7 
  8     # The internal self.__map dict maps keys to links in a doubly linked list.
  9     # The circular doubly linked list starts and ends with a sentinel element.
 10     # The sentinel element never gets deleted (this simplifies the algorithm).
 11     # The sentinel is in self.__hardroot with a weakref proxy in self.__root.
 12     # The prev links are weakref proxies (to prevent circular references).
 13     # Individual links are kept alive by the hard reference in self.__map.
 14     # Those hard references disappear when a key is deleted from an OrderedDict.
 15 
 16     def __init__(*args, **kwds):
 17         ‘‘‘Initialize an ordered dictionary.  The signature is the same as
 18         regular dictionaries, but keyword arguments are not recommended because
 19         their insertion order is arbitrary.
 20 
 21         ‘‘‘
 22         if not args:
 23             raise TypeError("descriptor ‘__init__‘ of ‘OrderedDict‘ object "
 24                             "needs an argument")
 25         self, *args = args
 26         if len(args) > 1:
 27             raise TypeError(expected at most 1 arguments, got %d % len(args))
 28         try:
 29             self.__root
 30         except AttributeError:
 31             self.__hardroot = _Link()
 32             self.__root = root = _proxy(self.__hardroot)
 33             root.prev = root.next = root
 34             self.__map = {}
 35         self.__update(*args, **kwds)
 36 
 37     def __setitem__(self, key, value,
 38                     dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
 39         od.__setitem__(i, y) <==> od[i]=y
 40         # Setting a new item creates a new link at the end of the linked list,
 41         # and the inherited dictionary is updated with the new key/value pair.
 42         if key not in self:
 43             self.__map[key] = link = Link()
 44             root = self.__root
 45             last = root.prev
 46             link.prev, link.next, link.key = last, root, key
 47             last.next = link
 48             root.prev = proxy(link)
 49         dict_setitem(self, key, value)
 50 
 51     def __delitem__(self, key, dict_delitem=dict.__delitem__):
 52         od.__delitem__(y) <==> del od[y]
 53         # Deleting an existing item uses self.__map to find the link which gets
 54         # removed by updating the links in the predecessor and successor nodes.
 55         dict_delitem(self, key)
 56         link = self.__map.pop(key)
 57         link_prev = link.prev
 58         link_next = link.next
 59         link_prev.next = link_next
 60         link_next.prev = link_prev
 61         link.prev = None
 62         link.next = None
 63 
 64     def __iter__(self):
 65         od.__iter__() <==> iter(od)
 66         # Traverse the linked list in order.
 67         root = self.__root
 68         curr = root.next
 69         while curr is not root:
 70             yield curr.key
 71             curr = curr.next
 72 
 73     def __reversed__(self):
 74         od.__reversed__() <==> reversed(od)
 75         # Traverse the linked list in reverse order.
 76         root = self.__root
 77         curr = root.prev
 78         while curr is not root:
 79             yield curr.key
 80             curr = curr.prev
 81 
 82     def clear(self):
 83         od.clear() -> None.  Remove all items from od.
 84         root = self.__root
 85         root.prev = root.next = root
 86         self.__map.clear()
 87         dict.clear(self)
 88 
 89     def popitem(self, last=True):
 90         ‘‘‘od.popitem() -> (k, v), return and remove a (key, value) pair.
 91         Pairs are returned in LIFO order if last is true or FIFO order if false.
 92 
 93         ‘‘‘
 94         if not self:
 95             raise KeyError(dictionary is empty)
 96         root = self.__root
 97         if last:
 98             link = root.prev
 99             link_prev = link.prev
100             link_prev.next = root
101             root.prev = link_prev
102         else:
103             link = root.next
104             link_next = link.next
105             root.next = link_next
106             link_next.prev = root
107         key = link.key
108         del self.__map[key]
109         value = dict.pop(self, key)
110         return key, value
111 
112     def move_to_end(self, key, last=True):
113         ‘‘‘Move an existing element to the end (or beginning if last==False).
114 
115         Raises KeyError if the element does not exist.
116         When last=True, acts like a fast version of self[key]=self.pop(key).
117 
118         ‘‘‘
119         link = self.__map[key]
120         link_prev = link.prev
121         link_next = link.next
122         link_prev.next = link_next
123         link_next.prev = link_prev
124         root = self.__root
125         if last:
126             last = root.prev
127             link.prev = last
128             link.next = root
129             last.next = root.prev = link
130         else:
131             first = root.next
132             link.prev = root
133             link.next = first
134             root.next = first.prev = link
135 
136     def __sizeof__(self):
137         sizeof = _sys.getsizeof
138         n = len(self) + 1                       # number of links including root
139         size = sizeof(self.__dict__)            # instance dictionary
140         size += sizeof(self.__map) * 2          # internal dict and inherited dict
141         size += sizeof(self.__hardroot) * n     # link objects
142         size += sizeof(self.__root) * n         # proxy objects
143         return size
144 
145     update = __update = MutableMapping.update
146 
147     def keys(self):
148         "D.keys() -> a set-like object providing a view on D‘s keys"
149         return _OrderedDictKeysView(self)
150 
151     def items(self):
152         "D.items() -> a set-like object providing a view on D‘s items"
153         return _OrderedDictItemsView(self)
154 
155     def values(self):
156         "D.values() -> an object providing a view on D‘s values"
157         return _OrderedDictValuesView(self)
158 
159     __ne__ = MutableMapping.__ne__
160 
161     __marker = object()
162 
163     def pop(self, key, default=__marker):
164         ‘‘‘od.pop(k[,d]) -> v, remove specified key and return the corresponding
165         value.  If key is not found, d is returned if given, otherwise KeyError
166         is raised.
167 
168         ‘‘‘
169         if key in self:
170             result = self[key]
171             del self[key]
172             return result
173         if default is self.__marker:
174             raise KeyError(key)
175         return default
176 
177     def setdefault(self, key, default=None):
178         od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od
179         if key in self:
180             return self[key]
181         self[key] = default
182         return default
183 
184     @_recursive_repr()
185     def __repr__(self):
186         od.__repr__() <==> repr(od)
187         if not self:
188             return %s() % (self.__class__.__name__,)
189         return %s(%r) % (self.__class__.__name__, list(self.items()))
190 
191     def __reduce__(self):
192         Return state information for pickling
193         inst_dict = vars(self).copy()
194         for k in vars(OrderedDict()):
195             inst_dict.pop(k, None)
196         return self.__class__, (), inst_dict or None, None, iter(self.items())
197 
198     def copy(self):
199         od.copy() -> a shallow copy of od
200         return self.__class__(self)
201 
202     @classmethod
203     def fromkeys(cls, iterable, value=None):
204         ‘‘‘OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
205         If not specified, the value defaults to None.
206 
207         ‘‘‘
208         self = cls()
209         for key in iterable:
210             self[key] = value
211         return self
212 
213     def __eq__(self, other):
214         ‘‘‘od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
215         while comparison to a regular mapping is order-insensitive.
216 
217         ‘‘‘
218         if isinstance(other, OrderedDict):
219             return dict.__eq__(self, other) and all(map(_eq, self, other))
220         return dict.__eq__(self, other)
View Code

常用功能示例代码:

技术分享
 1 import collections
 2 #   OrderedDict有序字典
 3 
 4 dic = collections.OrderedDict()
 5 dic[k1] = v1
 6 dic[k2] = v2
 7 dic[k3] = v3
 8 
 9 print(dic)
10 
11 #   move_to_end()
12 dic.move_to_end(k1)
13 print(dic)
14 
15 ret = dic.popitem()
16 print(dic,ret)   #这个栈是先进先出,同时这里popitem()返回的是item
17 
18 ret = dic.pop(k2)
19 print(dic,ret)  #这里pop()返回的是对应的value
View Code

默认字典defaultdict

默认字典defaultdict是对字典的类型的补充,他默认给字典的值value设置了一个类型。

1 >>> dic = collections.defaultdict(list)
2 >>> dic[k1].append(Tom)
3 >>> dic
4 defaultdict(<class list>, {k1: [Tom]})

可命名元组namedtuple

在模块collections中并未对namedtuple提供类属型,故使用前应先创建一个类:

1 #可命名元组namedtuple(),python中并未对其提供具体的类属性,故使用前应先创建一个类
2 MytupleClass = collections.namedtuple(MytupleClass,[x,y,z])
3 #上述语句,创建了一个名为MytupleClass的类
4 obj = MytupleClass(11,22,33)
5 print(obj.x)
6 print(obj.y)
7 print(obj.z)
8 
9 # print(help(MytupleClass)) #查看新创建的这个类MytupleClass的function

可命名元组namedtuple继承了元组tuple的类,亦不可修改!

双向队列deque

双向队列deque:

技术分享
  1 class deque(object):
  2     """
  3     deque([iterable[, maxlen]]) --> deque object
  4     
  5     A list-like sequence optimized for data accesses near its endpoints.
  6     """
  7     def append(self, *args, **kwargs): # real signature unknown
  8         """ Add an element to the right side of the deque. """
  9         pass
 10 
 11     def appendleft(self, *args, **kwargs): # real signature unknown
 12         """ Add an element to the left side of the deque. """
 13         pass
 14 
 15     def clear(self, *args, **kwargs): # real signature unknown
 16         """ Remove all elements from the deque. """
 17         pass
 18 
 19     def copy(self, *args, **kwargs): # real signature unknown
 20         """ Return a shallow copy of a deque. """
 21         pass
 22 
 23     def count(self, value): # real signature unknown; restored from __doc__
 24         """ D.count(value) -> integer -- return number of occurrences of value """
 25         return 0
 26 
 27     def extend(self, *args, **kwargs): # real signature unknown
 28         """ Extend the right side of the deque with elements from the iterable """
 29         pass
 30 
 31     def extendleft(self, *args, **kwargs): # real signature unknown
 32         """ Extend the left side of the deque with elements from the iterable """
 33         pass
 34 
 35     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 36         """
 37         D.index(value, [start, [stop]]) -> integer -- return first index of value.
 38         Raises ValueError if the value is not present.
 39         """
 40         return 0
 41 
 42     def insert(self, index, p_object): # real signature unknown; restored from __doc__
 43         """ D.insert(index, object) -- insert object before index """
 44         pass
 45 
 46     def pop(self, *args, **kwargs): # real signature unknown
 47         """ Remove and return the rightmost element. """
 48         pass
 49 
 50     def popleft(self, *args, **kwargs): # real signature unknown
 51         """ Remove and return the leftmost element. """
 52         pass
 53 
 54     def remove(self, value): # real signature unknown; restored from __doc__
 55         """ D.remove(value) -- remove first occurrence of value. """
 56         pass
 57 
 58     def reverse(self): # real signature unknown; restored from __doc__
 59         """ D.reverse() -- reverse *IN PLACE* """
 60         pass
 61 
 62     def rotate(self, *args, **kwargs): # real signature unknown
 63         """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """
 64         pass
 65 
 66     def __add__(self, *args, **kwargs): # real signature unknown
 67         """ Return self+value. """
 68         pass
 69 
 70     def __bool__(self, *args, **kwargs): # real signature unknown
 71         """ self != 0 """
 72         pass
 73 
 74     def __contains__(self, *args, **kwargs): # real signature unknown
 75         """ Return key in self. """
 76         pass
 77 
 78     def __copy__(self, *args, **kwargs): # real signature unknown
 79         """ Return a shallow copy of a deque. """
 80         pass
 81 
 82     def __delitem__(self, *args, **kwargs): # real signature unknown
 83         """ Delete self[key]. """
 84         pass
 85 
 86     def __eq__(self, *args, **kwargs): # real signature unknown
 87         """ Return self==value. """
 88         pass
 89 
 90     def __getattribute__(self, *args, **kwargs): # real signature unknown
 91         """ Return getattr(self, name). """
 92         pass
 93 
 94     def __getitem__(self, *args, **kwargs): # real signature unknown
 95         """ Return self[key]. """
 96         pass
 97 
 98     def __ge__(self, *args, **kwargs): # real signature unknown
 99         """ Return self>=value. """
100         pass
101 
102     def __gt__(self, *args, **kwargs): # real signature unknown
103         """ Return self>value. """
104         pass
105 
106     def __iadd__(self, *args, **kwargs): # real signature unknown
107         """ Implement self+=value. """
108         pass
109 
110     def __imul__(self, *args, **kwargs): # real signature unknown
111         """ Implement self*=value. """
112         pass
113 
114     def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
115         """
116         deque([iterable[, maxlen]]) --> deque object
117         
118         A list-like sequence optimized for data accesses near its endpoints.
119         # (copied from class doc)
120         """
121         pass
122 
123     def __iter__(self, *args, **kwargs): # real signature unknown
124         """ Implement iter(self). """
125         pass
126 
127     def __len__(self, *args, **kwargs): # real signature unknown
128         """ Return len(self). """
129         pass
130 
131     def __le__(self, *args, **kwargs): # real signature unknown
132         """ Return self<=value. """
133         pass
134 
135     def __lt__(self, *args, **kwargs): # real signature unknown
136         """ Return self<value. """
137         pass
138 
139     def __mul__(self, *args, **kwargs): # real signature unknown
140         """ Return self*value.n """
141         pass
142 
143     @staticmethod # known case of __new__
144     def __new__(*args, **kwargs): # real signature unknown
145         """ Create and return a new object.  See help(type) for accurate signature. """
146         pass
147 
148     def __ne__(self, *args, **kwargs): # real signature unknown
149         """ Return self!=value. """
150         pass
151 
152     def __reduce__(self, *args, **kwargs): # real signature unknown
153         """ Return state information for pickling. """
154         pass
155 
156     def __repr__(self, *args, **kwargs): # real signature unknown
157         """ Return repr(self). """
158         pass
159 
160     def __reversed__(self): # real signature unknown; restored from __doc__
161         """ D.__reversed__() -- return a reverse iterator over the deque """
162         pass
163 
164     def __rmul__(self, *args, **kwargs): # real signature unknown
165         """ Return self*value. """
166         pass
167 
168     def __setitem__(self, *args, **kwargs): # real signature unknown
169         """ Set self[key] to value. """
170         pass
171 
172     def __sizeof__(self): # real signature unknown; restored from __doc__
173         """ D.__sizeof__() -- size of D in memory, in bytes """
174         pass
175 
176     maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
177     """maximum size of a deque or None if unbounded"""
178 
179 
180     __hash__ = None
View Code

 常用功能代码示例:

  

 1 >>> import collections
 2 >>> que = collections.deque()
 3 >>> que.append(Jack1)
 4 >>> que.appendleft(Tom0)
 5 >>> que
 6 deque([Tom0, Jack1])
 7 >>> que.extend([li2,lin3])
 8 >>> que
 9 deque([Tom0, Jack1, li2, lin3])
10 >>> que.count(li2)
11 1
12 >>> que.insert(4,stphen4)
13 >>> que
14 deque([Tom0, Jack1, li2, lin3, stphen4])
15 >>> que.rotate(2) #循环右移n次
16 >>> que
17 deque([lin3, stphen4, Tom0, Jack1, li2])

 

队列queue分为单向队列Queue与双向队列deque:

技术分享

单向队列Queue

如:

 1 >>> import queue
 2 >>> obj = queue.Queue()
 3 >>> obj.put(jack)
 4 >>> obj.put(lin)
 5 >>> obj.put(tom)
 6 >>> obj.get()
 7 jack
 8 >>> obj.get()
 9 lin
10 >>> obj.get()#先进先出,后进后出
11 tom

 

技术分享
  1 class Queue:
  2     ‘‘‘Create a queue object with a given maximum size.
  3 
  4     If maxsize is <= 0, the queue size is infinite.
  5     ‘‘‘
  6 
  7     def __init__(self, maxsize=0):
  8         self.maxsize = maxsize
  9         self._init(maxsize)
 10 
 11         # mutex must be held whenever the queue is mutating.  All methods
 12         # that acquire mutex must release it before returning.  mutex
 13         # is shared between the three conditions, so acquiring and
 14         # releasing the conditions also acquires and releases mutex.
 15         self.mutex = threading.Lock()
 16 
 17         # Notify not_empty whenever an item is added to the queue; a
 18         # thread waiting to get is notified then.
 19         self.not_empty = threading.Condition(self.mutex)
 20 
 21         # Notify not_full whenever an item is removed from the queue;
 22         # a thread waiting to put is notified then.
 23         self.not_full = threading.Condition(self.mutex)
 24 
 25         # Notify all_tasks_done whenever the number of unfinished tasks
 26         # drops to zero; thread waiting to join() is notified to resume
 27         self.all_tasks_done = threading.Condition(self.mutex)
 28         self.unfinished_tasks = 0
 29 
 30     def task_done(self):
 31         ‘‘‘Indicate that a formerly enqueued task is complete.
 32 
 33         Used by Queue consumer threads.  For each get() used to fetch a task,
 34         a subsequent call to task_done() tells the queue that the processing
 35         on the task is complete.
 36 
 37         If a join() is currently blocking, it will resume when all items
 38         have been processed (meaning that a task_done() call was received
 39         for every item that had been put() into the queue).
 40 
 41         Raises a ValueError if called more times than there were items
 42         placed in the queue.
 43         ‘‘‘
 44         with self.all_tasks_done:
 45             unfinished = self.unfinished_tasks - 1
 46             if unfinished <= 0:
 47                 if unfinished < 0:
 48                     raise ValueError(task_done() called too many times)
 49                 self.all_tasks_done.notify_all()
 50             self.unfinished_tasks = unfinished
 51 
 52     def join(self):
 53         ‘‘‘Blocks until all items in the Queue have been gotten and processed.
 54 
 55         The count of unfinished tasks goes up whenever an item is added to the
 56         queue. The count goes down whenever a consumer thread calls task_done()
 57         to indicate the item was retrieved and all work on it is complete.
 58 
 59         When the count of unfinished tasks drops to zero, join() unblocks.
 60         ‘‘‘
 61         with self.all_tasks_done:
 62             while self.unfinished_tasks:
 63                 self.all_tasks_done.wait()
 64 
 65     def qsize(self):
 66         #查看并返回队列中的数据个数
 67         ‘‘‘Return the approximate size of the queue (not reliable!).‘‘‘
 68         with self.mutex:
 69             return self._qsize()
 70 
 71     def empty(self):
 72         ‘‘‘Return True if the queue is empty, False otherwise (not reliable!).
 73 
 74         This method is likely to be removed at some point.  Use qsize() == 0
 75         as a direct substitute, but be aware that either approach risks a race
 76         condition where a queue can grow before the result of empty() or
 77         qsize() can be used.
 78 
 79         To create code that needs to wait for all queued tasks to be
 80         completed, the preferred technique is to use the join() method.
 81         ‘‘‘
 82         with self.mutex:
 83             return not self._qsize()
 84 
 85     def full(self):
 86         ‘‘‘Return True if the queue is full, False otherwise (not reliable!).
 87 
 88         This method is likely to be removed at some point.  Use qsize() >= n
 89         as a direct substitute, but be aware that either approach risks a race
 90         condition where a queue can shrink before the result of full() or
 91         qsize() can be used.
 92         ‘‘‘
 93         with self.mutex:
 94             return 0 < self.maxsize <= self._qsize()
 95 
 96     def put(self, item, block=True, timeout=None):
 97         ‘‘‘Put an item into the queue.
 98 
 99         If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
100         block if necessary until a free slot is available. If ‘timeout‘ is
101         a non-negative number, it blocks at most ‘timeout‘ seconds and raises
102         the Full exception if no free slot was available within that time.
103         Otherwise (‘block‘ is false), put an item on the queue if a free slot
104         is immediately available, else raise the Full exception (‘timeout‘
105         is ignored in that case).
106         ‘‘‘
107         with self.not_full:
108             if self.maxsize > 0:
109                 if not block:
110                     if self._qsize() >= self.maxsize:
111                         raise Full
112                 elif timeout is None:
113                     while self._qsize() >= self.maxsize:
114                         self.not_full.wait()
115                 elif timeout < 0:
116                     raise ValueError("‘timeout‘ must be a non-negative number")
117                 else:
118                     endtime = time() + timeout
119                     while self._qsize() >= self.maxsize:
120                         remaining = endtime - time()
121                         if remaining <= 0.0:
122                             raise Full
123                         self.not_full.wait(remaining)
124             self._put(item)
125             self.unfinished_tasks += 1
126             self.not_empty.notify()
127 
128     def get(self, block=True, timeout=None):
129         #取出一个数据,由于单向,故get()无参数
130         ‘‘‘Remove and return an item from the queue.
131 
132         If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
133         block if necessary until an item is available. If ‘timeout‘ is
134         a non-negative number, it blocks at most ‘timeout‘ seconds and raises
135         the Empty exception if no item was available within that time.
136         Otherwise (‘block‘ is false), return an item if one is immediately
137         available, else raise the Empty exception (‘timeout‘ is ignored
138         in that case).
139         ‘‘‘
140         with self.not_empty:
141             if not block:
142                 if not self._qsize():
143                     raise Empty
144             elif timeout is None:
145                 while not self._qsize():
146                     self.not_empty.wait()
147             elif timeout < 0:
148                 raise ValueError("‘timeout‘ must be a non-negative number")
149             else:
150                 endtime = time() + timeout
151                 while not self._qsize():
152                     remaining = endtime - time()
153                     if remaining <= 0.0:
154                         raise Empty
155                     self.not_empty.wait(remaining)
156             item = self._get()
157             self.not_full.notify()
158             return item
159 
160     def put_nowait(self, item):
161         ‘‘‘Put an item into the queue without blocking.
162 
163         Only enqueue the item if a free slot is immediately available.
164         Otherwise raise the Full exception.
165         ‘‘‘
166         return self.put(item, block=False)
167 
168     def get_nowait(self):
169         ‘‘‘Remove and return an item from the queue without blocking.
170 
171         Only get an item if one is immediately available. Otherwise
172         raise the Empty exception.
173         ‘‘‘
174         return self.get(block=False)
View Code

 

[python_Day2]

标签:

原文地址:http://www.cnblogs.com/loveclear/p/5767245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!