Python基本数据类型(一)
一、int的函数说明(部分函数Python2特有,Python3已删除,部分函数Python3新增;)
class int(object):
"""
int(x=0) -> int or long
int(x=0) -> integer (Python3) Python2和Python3的用法一致,在Python2中,主要将数字或字符串转换为整数,如果没有给出参数,则返回0;如果x是浮点数,则先截断小数点在进行转换;如果x在整数范围之外,函数将返回long;在Python3中,主要将一个数字或字符串转换为整数,如果没有参数,返回0;如果x是一个数,返回X __int__();如果x是浮点数,则先截断小数点在进行转换;
例如(python2):
>>> int()
>>> int(1.9)
>>> int(2**63)
9223372036854775808L
>>> int(x = 0)
>>> int(x = 1.9)
>>> int(x = 2**63)
9223372036854775808L 例如(python3):
>>> int()
>>> int(1.9)
>>> int(2**63)
>>> int(x = 0)
>>> int(x = 1.9)
>>> int(x = 2**63)
int(x, base=10) -> int or long
int(x, base=10) -> integer Python2和Python3的用法一致,主要将浮点数或数字字符串转换为整数,如果参数x不是一个数字,必须是字符串、数组bytes或bytearray类型,可以在x可以在前面加上“+”或“-”来表示正数及负数;base参数必须是整数,表示字符串参数的进制,有效值为0和2-36,默认10就是表示使用十进制;当它是2时,表示二进制的字符串转换。当它是8时,表示是八进制的字符串转换。当它是16时,表示是十六进制的字符串转换。当它是0时,它表示不是0进制,而是按照十进制进行转换;
例如:
>>> int('100',base = 2)
>>> int('100',base = 0)
>>> int('100',base = 8)
>>> int('100',base = 10)
>>> int('a',base = 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
不是数字字符串会产生报错;
>>> int('-100',base = 8)
-64
>>> int('+100',base = 8)
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""
int.bit_length() -> int 返回表示该数字的时占用的最少位数;
例如:
>>> int(10)
>>> (10).bit_length()
>>> bin(10)
'0b1010'
"""
return 0
def conjugate(self, *args, **kwargs): # real signature unknown
""" 返回该复数的共轭复数; """
pass
def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.from_bytes(bytes, byteorder, *, signed=False) -> int (Python3新增) 返回给定的字节数组所表示的整数;
bytes参数必须是一个类似字节的对象(例如字节或bytearray);
byteorder参数确定用于表示整数的字节顺序。如果字节序是'big',最高有效字节排在在字节数组最开始。如果字节序是'little',则最高有效字节排在字节数组的结尾。如果要要求按照主机系统的本地字节顺序排序,则需使用'sys.byteorder'作为字节顺序值;
signed参数指示是否使用二进制补码表示整数;
例如:
>>> int.from_bytes(b'\x00\x10', byteorder='big')
>>> int.from_bytes(b'\x00\x10', byteorder='little')
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
>>> int.from_bytes([255, 0, 0], byteorder='big')
"""
pass
def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.to_bytes(length, byteorder, *, signed=False) -> bytes (Python3新增) 返回一个表示整数的字节数组;
用字节长度表示整数。如果整数不能用给定的字节数表示,则会引发OverflowError;
byteorder参数确定用于表示整数的字节顺序。如果字节序是'big',最高有效字节排在在字节数组最开始。如果字节序是'little',则最高有效字节排在字节数组的结尾。如果要要求按照主机系统的本地字节顺序排序,则需使用'sys.byteorder'作为字节顺序值;
signed参数确定是否使用二进制补码表示整数。如果signed是False,并给出一个负整数,则会引发一个OverflowError。 signed的默认值为False;
例如:
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03
>>> (-1024).to_bytes(10, byteorder='big')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: can't convert negative int to unsigned
"""
pass
def __abs__(self): # real signature unknown; restored from __doc__
"""
x.__abs__() 等同于 abs(x) 返回绝对值,参数可以是:负数、正数、浮点数或者长整形;
例如:
>>> x = -2
>>> x.__abs__()
>>> abs(x)
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
"""
x.__add__(y) 等同于 x+y 加法;
例如:
>>> x = 2
>>> y = 4
>>> x.__add__(y)
>>> x + y """
pass
def __and__(self, y): # real signature unknown; restored from __doc__
"""
x.__and__(y) 等同于 x&y 按位与;
例如:
>>> x = 60
>>> y = 13
>>> bin(x)
'0b111100'
>>> bin(y)
'0b1101'
>>> x.__and__(y)
>>> x & y
"""
pass
def __cmp__(self, y): # real signature unknown; restored from __doc__
"""
x.__cmp__(y) <==> cmp(x,y) (Python2特有,Python3已删除) 比较两个对象x和y,如果x < y ,返回负数;x == y, 返回0;x > y,返回正数;
例如:
>>> x = 10
>>> y = 20
>>> x.__cmp__(y)
-1
>>> y.__cmp__(x)
>>> cmp(x,y)
-1
>>> cmp(y,x)
>>> y = 10
>>> x.__cmp__(y)
>>> cmp(x,y)
"""
pass
def __coerce__(self, y): # real signature unknown; restored from __doc__
"""
x.__coerce__(y) <==> coerce(x, y) (Python2特有,Python3已删除) 强制生成一个元组;
例如:
>>> x = 10
>>> y = 20
>>> x.__coerce__(y)
(10, 20)
>>> coerce(x,y)
(10, 20)
"""
pass
def __bool__(self, *args, **kwargs): # real signature unknown
"""
self != 0 (Python3新增) 布尔型判断;
例如:
>>> a = True
>>> b = False
>>> a.__bool__()
True
>>> b.__bool__()
False
>>> x = 0
>>> b = x > 1
>>> b.__bool__()
False
"""
pass
def __ceil__(self, *args, **kwargs): # real signature unknown
"""
返回数字的上入整数,如果数值是小数,则返回的数值是整数加一,配合math函数使用; (Python3新增)
例如:
>>> import math
>>> math.ceil(4.1) """
def __divmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__divmod__(y) 等同于 divmod(x, y) 数字相除,将商和余数返回一个数组,相当于 x//y ,返回(商,余数)
例如:
>>> x = 10
>>> y = 11
>>> x.__divmod__(y)
(0, 10)
>>> divmod(x,y)
(0, 10)
"""
pass
def __div__(self, y): # real signature unknown; restored from __doc__
"""
x.__div__(y) 等同于 x/y (Python2特有,Python3已删除) 数字相除,返回商;
例如:
>>> x = 10
>>> y = 9
>>> x.__div__(y)
>>> div(x,y)
>>> x / y
"""
pass
def __eq__(self, *args, **kwargs): # real signature unknown
"""
Return self==value. (Python3新增) 用于判断数值是否相等,返回布尔值,等价于 x == y;
例如:
>>> x = 10
>>> y = 11
>>> x.__eq__(y)
False
>>> z = 10
>>> x.__eq__(z)
True
"""
pass
def __float__(self): # real signature unknown; restored from __doc__
"""
x.__float__() <==> float(x) 转换为浮点类型,即小数型;
例如:
>>> x = 1.4
>>> x.__float__()
1.4
>>> float(x)
1.4
>>> y = 2
>>> y.__float__()
2.0
>>> float(y)
2.0
"""
pass
def __floordiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__floordiv__(y) 等同于 x//y 用于数字相除取其商,例如, 4//3 返回 1;
例如:
>>> x = 9
>>> y = 7
>>> x.__floordiv__(y)
>>> x // y
"""
pass
def __floor__(self, *args, **kwargs): # real signature unknown
"""
Flooring an Integral returns itself. (Python3新增) 返回数字的下舍整数,配合math函数使用;
例如:
>>> import math
>>> x = 1.54
>>> math.floor(x)
"""
pass
def __format__(self, *args, **kwargs): # real signature unknown
"""
无意义;
"""
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
"""
内部调用 __new__方法或创建对象时传入参数使用;
"""
pass
def __ge__(self, *args, **kwargs): # real signature unknown
"""
Return self>=value. (Python3新增) 数字判断大于等于,相当于 x >= y,返回布尔值;
例如:
>>> x = 4
>>> y = 4
>>> x.__ge__(y)
True
>>> x >= y
True
>>> x = 5
>>> x.__ge__(y)
True
>>> x >= y
True
>>> y = 7
>>> x.__ge__(y)
False
>>> x >= y
False
"""
pass
def __gt__(self, *args, **kwargs): # real signature unknown
"""
Return self>value. (Python3新增) 数字大于判断,相当于 x > y,返回布尔值;
例如:
>>> x = 10
>>> y = 9
>>> x.__gt__(y)
True
>>> y.__gt__(x)
False
>>> x > y
True
>>> y < x
False
>>> x = 4
>>> y = 4
>>> x > y
False
>>> x.__gt__(y)
False
"""
pass
def __hash__(self): # real signature unknown; restored from __doc__
"""
x.__hash__() <==> hash(x) 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等;
"""
pass
def __hex__(self): # real signature unknown; restored from __doc__
"""
x.__hex__() 等同于 hex(x) 返回当前数的十六进制表示; (Python2特有,Python3已删除)
例如:
>>> x = 100
>>> x.__hex__()
'0x64'
>>> hex(x)
'0x64'
"""
pass
def __index__(self): # real signature unknown; restored from __doc__
"""
x[y:z] <==> x[y.__index__():z.__index__()] 用于切片,数字无意义;
"""
pass
def __init__(self, x, base=10): # known special case of int.__init__
"""
构造方法,执行 x = 123 或 x = int(10) 时,自动调用;
"""
pass
def __int__(self): # real signature unknown; restored from __doc__
"""
x.__int__() 等同于 int(x) 转换为整数;
"""
pass
def __invert__(self): # real signature unknown; restored from __doc__
"""
x.__invert__() 等同于 ~x 数字取反操作;
例如:
>>> x = 10
>>> x.__invert__()
-11
>>> ~x
-11
"""
pass
def __long__(self): # real signature unknown; restored from __doc__
"""
x.__long__() 等同于 long(x) 转换为长整数; (Python2特有,Python3已删除)
例如:
>>> x = 10
>>> x.__long__()
10L
>>> long(x)
10L
"""
pass
def __le__(self, *args, **kwargs): # real signature unknown
"""
Return self<=value. (Python3新增) 数字小于等于判断,相当于 x <= y,返回布尔值;
例如:
>>> x = 2
>>> y = 4
>>> x.__le__(y)
True
>>> x <= y
True
>>> y.__le__(x)
False
>>> y <= x
False
>>> y = 2
>>> x.__le__(y)
True
>>> x <= y
True
"""
pass
def __lshift__(self, y): # real signature unknown; restored from __doc__
"""
x.__lshift__(y) 等同于 x<<y 实现一个位左移操作的功能,即x向左移动y位;
例如:
>>> x = 2
>>> y = 1
>>> bin(x)
'0b10'
>>> x.__lshift__(y)
>>> z = x.__lshift__(y)
>>> bin(y)
'0b100'
>>> y = 2
>>> z = x.__lshift__(y)
>>> x.__lshift__(y)
>>> bin(z)
'0b1000'
"""
pass
def __lt__(self, *args, **kwargs): # real signature unknown
"""
Return self<value. 数字小于判断,相当于 x < y,返回布尔值; (Python3新增)
例如:
>>> x = 2
>>> y = 4
>>> x.__lt__(y)
True
>>> x < y
True
>>> y.__lt__(x)
False
>>> y < x
False
"""
pass
def __mod__(self, y): # real signature unknown; restored from __doc__
"""
x.__mod__(y) 等同于 x%y 实现一个“%”操作符代表的取模操作;
例如:
>>> x = 7
>>> y = 3
>>> x.__mod__(y)
>>> x % y
"""
pass
def __mul__(self, y): # real signature unknown; restored from __doc__
"""
x.__mul__(y) 等同于 x*y 实现乘法;
例如:
>>> x = 2
>>> y = 4
>>> x.__mul__(y)
>>> x * y
"""
pass
def __neg__(self): # real signature unknown; restored from __doc__
"""
x.__neg__() 等同于 -x 数字取负操作;
例如:
>>> x = 3
>>> x.__neg__()
-3
>>> -x
-3
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
__new__方法接受的参数虽然也是和__init__一样,但__init__是在类实例创建之后调用,而__new__方法正是创建这个类实例的方法;__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple),提供给你一个自定义这些类的实例化过程的途径;
"""
pass
def __ne__(self, *args, **kwargs): # real signature unknown
"""
Return self!=value. 数字不相等判断,相当于x != y,返回布尔值; (Python3新增)
例如:
>>> x = 2
>>> y = 4
>>> x.__ne__(y)
True
>>> x != y
True
>>> y =2
>>> x.__ne__(y)
False
>>> x != y
False
"""
pass
def __nonzero__(self): # real signature unknown; restored from __doc__
"""
x.__nonzero__() 等同于 x != 0 数字不等于0判断,相当于x != 0,返回布尔值; (Python2特有,Python3已删除)
例如:
>>> x = 2
>>> x.__nonzero__()
True
>>> x != 0
True
>>> x = 0
>>> x.__nonzero__()
False
>>> x != 0
False
"""
pass
def __oct__(self): # real signature unknown; restored from __doc__
"""
x.__oct__() 等同于 oct(x) 返回当前数的八进制表示; (Python2特有,Python3已删除)
例如:
>>> x = 17
>>> x.__oct__()
'021'
>>> oct(x)
'021'
"""
pass
def __or__(self, y): # real signature unknown; restored from __doc__
"""
x.__or__(y) 等同于 x|y 按位或;
例如:
>>> x = 3
>>> y = 5
>>> bin(x)
'0b11'
>>> bin(y)
'0b101'
>>> x.__or__(y)
>>> x|y
>>> a = x.__or__(y)
>>> bin(a)
'0b111'
"""
pass
def __pos__(self): # real signature unknown; restored from __doc__
"""
x.__pos__() 等同于 +x 数字取正操作;
"""
pass
def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
"""
x.__pow__(y[, z]) 等同于 pow(x, y[, z]) 幂,次方,计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,也可以配合math函数使用;pow()通过内置的方法直接调用,内置方法会把参数作为整型,而math模块则会把参数转换为float;
例如:
>>> x = 2
>>> y = 4
>>> pow(x,y)
>>> z = 3
>>> pow(x,y,z)
>>> import math
>>> math.pow(x,y)
16.0
"""
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
"""
x.__radd__(y) 等同于 y+x 右加法;
例如:
>>> x = 2
>>> y = 1
>>> x.__radd__(y)
>>> y + x
"""
pass
def __rand__(self, y): # real signature unknown; restored from __doc__
"""
x.__rand__(y) 等同于 y&x 按位右与;
例如:
>>> x = 63
>>> y = 13
>>> bin(x)
'0b111111'
>>> bin(y)
'0b1101'
>>> x.__rand__(y)
>>> y & x
>>> a = x.__rand__(y)
>>> bin(a)
'0b1101'
>>> a = x & y
>>> bin(a)
'0b1101'
"""
pass
def __rdivmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__rdivmod__(y) 等同于 divmod(y, x) 数字相除,将商和余数返回一个数组,相当于 y//x ,返回(商,余数)
"""
pass
def __rdiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rdiv__(y) 等同于 y/x 数字相除,返回商; (Python2特有,Python3已删除)
"""
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,即转换为字符串类型;
例如:
>>> x = 2.0
>>> repr(x)
'2.0'
>>> a = repr(x)
>>> type(a)
<type 'str'>
"""
pass
def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rfloordiv__(y) 等同于 y//x 用于数字相除取其商;
"""
pass
def __rlshift__(self, y): # real signature unknown; restored from __doc__
"""
x.__rlshift__(y) 等同于 y<<x 实现一个位左移操作的功能,即y向左移动x位;
例如:
>>> x = 1
>>> y = 2
>>> bin(y)
'0b10'
>>> x.__rlshift__(y)
>>> z = x.__rlshift__(y)
>>> bin(z)
'0b100'
>>> z = y << x
>>> bin(z)
'0b100'
>>> x = 2
>>> z = x.__rlshift__(y)
>>> bin(z)
'0b1000'
"""
pass
def __rmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmod__(y) 等同于 y%x 实现一个右“%”操作符代表的取模操作;
"""
pass
def __rmul__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmul__(y) 等同于 y*x 实现右乘法;
"""
pass
def __ror__(self, y): # real signature unknown; restored from __doc__
"""
x.__ror__(y) 等同于 y|x 按位右或;
"""
pass
def __round__(self, *args, **kwargs): # real signature unknown
"""
x.__rount__() 等同于 round( x [, n] ) 返回浮点数x的四舍五入值,n参数表示保留的小数点位数; (Python3新增)
例如:
>>> x = 2.56
>>> x.__round__()
>>> x.__round__(1)
2.6
>>> x.__round__(2)
2.56
>>> round(x)
>>> round(x,1)
2.6
>>> round(x,2)
2.56
"""
pass
def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
"""
y.__rpow__(x[, z]) 等同于 pow(x, y[, z]) 幂,次方,计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,也可以配合math函数使用;pow()通过内置的方法直接调用,内置方法会把参数作为整型,而math模块则会把参数转换为float;
"""
pass
def __rrshift__(self, y): # real signature unknown; restored from __doc__
"""
x.__rrshift__(y) 等同于 y>>x 实现一个位右移操作的功能,即y向右移动x位;
例如:
>>> x = 1
>>> y = 4
>>> bin(y)
'0b100'
>>> x.__rrshift__(y)
>>> z = x.__rrshift__(y)
>>> bin(z)
'0b10'
>>> y >> x
>>> z = y >> x
>>> bin(z)
'0b10'
"""
pass
def __rshift__(self, y): # real signature unknown; restored from __doc__
"""
x.__rshift__(y) 等同于 x>>y 实现一个位右移操作的功能,即x向右移动y位;
例如:
>>> x = 4
>>> y = 1
>>> bin(x)
'0b100'
>>> x.__rshift__(y)
>>> z = x.__rrshift__(y)
>>> bin(z)
'0b10'
>>> x >> y
>>> z = x >> y
>>> bin(z)
'0b10'
"""
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
"""
x.__rsub__(y) 等同于 y-x 右减法,相当于y减x;
例如:
>>> x = 4
>>> y = 1
>>> x.__rsub__(y)
-3
>>> y - x
-3
"""
pass
def __rtruediv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rtruediv__(y) 等同于 y/x 右除法,相当于y除以x;
"""
pass
def __rxor__(self, y): # real signature unknown; restored from __doc__
"""
x.__rxor__(y) 等同于 y^x 按位右异或,相当于y按x进行异或;
"""
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
"""
返回内存中的大小(以字节为单位); (Python2存在于long函数,Python3中合并进int函数)
"""
def __str__(self): # real signature unknown; restored from __doc__
"""
x.__str__() 等同于 str(x) 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式,即转换为字符串类型;
例如:
>>> x = 1
>>> x.__str__()
'1'
>>> a = x.__str__()
>>> type(a)
<type 'str'>
>>> a = str(x)
>>> type(a)
<type 'str'>
"""
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
"""
x.__sub__(y) <==> x-y 减法,相当于x减y;
"""
pass
def __truediv__(self, y): # real signature unknown; restored from __doc__
"""
x.__truediv__(y) <==> x/y 除法,相当于x除以y;
"""
pass
def __trunc__(self, *args, **kwargs): # real signature unknown
"""
返回数值被截取为整形的值,在整形中无意义;
"""
pass
def __xor__(self, y): # real signature unknown; restored from __doc__
"""
x.__xor__(y) 等同于 x^y 按位异或,相当于x按y进行异或;
"""
pass
denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
分母,等于1;
"""
imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
虚数,无意义;
"""
numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
分子,等于数字大小;
"""
real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
实数,无意义;
"""
int
二、long的函数说明(函数与方法与int一致,Python3已与int类型进行合并;)
class long(object):
"""
long(x=0) -> long
long(x, base=10) -> long Convert a number or string to a long integer, or return 0L if no arguments
are given. If x is floating point, the conversion truncates towards zero. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4L
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""
long.bit_length() -> int or long Number of bits necessary to represent self in binary.
>>> bin(37L)
'0b100101'
>>> (37L).bit_length()
6
"""
return 0
def conjugate(self, *args, **kwargs): # real signature unknown
""" Returns self, the complex conjugate of any long. """
pass
def __abs__(self): # real signature unknown; restored from __doc__
""" x.__abs__() <==> abs(x) """
pass
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __and__(self, y): # real signature unknown; restored from __doc__
""" x.__and__(y) <==> x&y """
pass
def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass
def __coerce__(self, y): # real signature unknown; restored from __doc__
""" x.__coerce__(y) <==> coerce(x, y) """
pass
def __divmod__(self, y): # real signature unknown; restored from __doc__
""" x.__divmod__(y) <==> divmod(x, y) """
pass
def __div__(self, y): # real signature unknown; restored from __doc__
""" x.__div__(y) <==> x/y """
pass
def __float__(self): # real signature unknown; restored from __doc__
""" x.__float__() <==> float(x) """
pass
def __floordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__floordiv__(y) <==> x//y """
pass
def __format__(self, *args, **kwargs): # real signature unknown
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __hex__(self): # real signature unknown; restored from __doc__
""" x.__hex__() <==> hex(x) """
pass
def __index__(self): # real signature unknown; restored from __doc__
""" x[y:z] <==> x[y.__index__():z.__index__()] """
pass
def __init__(self, x=0): # real signature unknown; restored from __doc__
pass
def __int__(self): # real signature unknown; restored from __doc__
""" x.__int__() <==> int(x) """
pass
def __invert__(self): # real signature unknown; restored from __doc__
""" x.__invert__() <==> ~x """
pass
def __long__(self): # real signature unknown; restored from __doc__
""" x.__long__() <==> long(x) """
pass
def __lshift__(self, y): # real signature unknown; restored from __doc__
""" x.__lshift__(y) <==> x<<y """
pass
def __mod__(self, y): # real signature unknown; restored from __doc__
""" x.__mod__(y) <==> x%y """
pass
def __mul__(self, y): # real signature unknown; restored from __doc__
""" x.__mul__(y) <==> x*y """
pass
def __neg__(self): # real signature unknown; restored from __doc__
""" x.__neg__() <==> -x """
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __nonzero__(self): # real signature unknown; restored from __doc__
""" x.__nonzero__() <==> x != 0 """
pass
def __oct__(self): # real signature unknown; restored from __doc__
""" x.__oct__() <==> oct(x) """
pass
def __or__(self, y): # real signature unknown; restored from __doc__
""" x.__or__(y) <==> x|y """
pass
def __pos__(self): # real signature unknown; restored from __doc__
""" x.__pos__() <==> +x """
pass
def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
""" x.__radd__(y) <==> y+x """
pass
def __rand__(self, y): # real signature unknown; restored from __doc__
""" x.__rand__(y) <==> y&x """
pass
def __rdivmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass
def __rdiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rdiv__(y) <==> y/x """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rfloordiv__(y) <==> y//x """
pass
def __rlshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rlshift__(y) <==> y<<x """
pass
def __rmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rmod__(y) <==> y%x """
pass
def __rmul__(self, y): # real signature unknown; restored from __doc__
""" x.__rmul__(y) <==> y*x """
pass
def __ror__(self, y): # real signature unknown; restored from __doc__
""" x.__ror__(y) <==> y|x """
pass
def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass
def __rrshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rrshift__(y) <==> y>>x """
pass
def __rshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rshift__(y) <==> x>>y """
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass
def __rtruediv__(self, y): # real signature unknown; restored from __doc__
""" x.__rtruediv__(y) <==> y/x """
pass
def __rxor__(self, y): # real signature unknown; restored from __doc__
""" x.__rxor__(y) <==> y^x """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Returns size in memory, in bytes """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass
def __truediv__(self, y): # real signature unknown; restored from __doc__
""" x.__truediv__(y) <==> x/y """
pass
def __trunc__(self, *args, **kwargs): # real signature unknown
""" Truncating an Integral returns itself. """
pass
def __xor__(self, y): # real signature unknown; restored from __doc__
""" x.__xor__(y) <==> x^y """
pass
denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the denominator of a rational number in lowest terms"""
imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the imaginary part of a complex number"""
numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the numerator of a rational number in lowest terms"""
real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the real part of a complex number"""
long
三、float的函数说明(函数与方法的使用与int类似;)
class float(object):
"""
float(x) -> 将字符串或数字转换为浮点数;
"""
def as_integer_ratio(self): # real signature unknown; restored from __doc__
"""
float.as_integer_ratio() -> (int, int) 获取值的最简化结果,返回一对整数,其比例完全等于原始浮点数,并使用正分母;在无穷大上产生OverflowError,在NaNs上产生ValueError;
例如:
>>> (10.0).as_integer_ratio()
(10, 1)
>>> (0.0).as_integer_ratio()
(0, 1)
>>> (-.25).as_integer_ratio()
(-1, 4)
"""
pass
def conjugate(self, *args, **kwargs): # real signature unknown
"""
返回该复数的共轭复数;
"""
pass
def fromhex(self, string): # real signature unknown; restored from __doc__
"""
float.fromhex(string) -> float 将十六进制转换为浮点数;
例如:
>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> float.fromhex('-0x1p-1074')
-4.9406564584124654e-324
"""
return 0.0
def hex(self): # real signature unknown; restored from __doc__
"""
float.hex() -> string 将浮点数转换为十六进制;
例如:
>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> 3.14159.hex()
'0x1.921f9f01b866ep+1'
"""
return ""
def is_integer(self, *args, **kwargs): # real signature unknown
"""
判断是不是整数,返回布尔值;
例如:
>>> x = 1.1
>>> x.is_integer()
False
>>> x = 2.0
>>> x.is_integer()
True
"""
pass
def __abs__(self): # real signature unknown; restored from __doc__
"""
x.__abs__() 等同于 abs(x) 返回绝对值,参数可以是:负数、正数、浮点数或者长整形;
例如:
>>> x = -1.1
>>> x.__abs__()
1.1
>>> abs(x)
1.1
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
"""
x.__add__(y) 等同于 x+y
"""
pass
def __coerce__(self, y): # real signature unknown; restored from __doc__
"""
x.__coerce__(y) 等同于 coerce(x, y) 强制生成一个元组; (Python2特有,Python3已删除)
例如:
>>> x = 1.1
>>> y = 2.2
>>> x.__coerce__(y)
(1.1, 2.2)
>>> coerce(x,y)
(1.1, 2.2)
"""
pass
def __bool__(self, *args, **kwargs): # real signature unknown
"""
self != 0 (Python3新增) 布尔型判断;
"""
pass
def __divmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__divmod__(y) 等同于 divmod(x, y) 数字相除,将商和余数返回一个数组,相当于 x//y ,返回(商,余数);
例如:
>>> x = 1.1
>>> y = 3.3
>>> x.__divmod__(y)
(0.0, 1.1)
>>> divmod(x,y)
(0.0, 1.1)
"""
pass
def __div__(self, y): # real signature unknown; restored from __doc__
"""
x.__div__(y) 等同于 x/y(Python2特有,Python3已删除) 数字相除,返回商;
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
"""
x.__eq__(y) 等同于 x==y 用于判断数值是否相等,返回布尔值,等价于 x == y;
"""
pass
def __float__(self): # real signature unknown; restored from __doc__
"""
x.__float__() 等同于 float(x) 转换为浮点类型,即小数型;
例如:
>>> x = 2
>>> x.__float__()
2.0
>>> float(x)
2.0
"""
pass
def __floordiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__floordiv__(y) 等同于 x//y 用于数字相除取其商;
"""
pass
def __format__(self, format_spec): # real signature unknown; restored from __doc__
"""
float.__format__(format_spec) -> string 无意义;
"""
return ""
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __getformat__(self, typestr): # real signature unknown; restored from __doc__
"""
float.__getformat__(typestr) -> string 你最好不要使用这个函数,它的主要存在Python中的的测试套件中;
typestr参数必须是'double'和'float'类型;
This function returns whichever of
'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
format of floating point numbers used by the C type named by typestr.
"""
return ""
def __getnewargs__(self, *args, **kwargs): # real signature unknown
"""
内部调用 __new__方法或创建对象时传入参数使用;
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
"""
x.__ge__(y) 等同于 x>=y 数字判断大于等于,相当于 x >= y,返回布尔值;
"""
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
"""
x.__gt__(y) 等同于 x>y 数字大于判断,相当于 x > y,返回布尔值;
"""
pass
def __hash__(self): # real signature unknown; restored from __doc__
"""
x.__hash__() 等同于 hash(x) 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等;
"""
pass
def __init__(self, x): # real signature unknown; restored from __doc__
"""
构造方法,执行 x = 1.1 或 x = float(1.1) 时,自动调用;
"""
pass
def __int__(self): # real signature unknown; restored from __doc__
"""
x.__int__() 等同于 int(x) 转换为整数;
"""
pass
def __le__(self, y): # real signature unknown; restored from __doc__
"""
x.__le__(y) 等同于 x<=y 数字小于等于判断,相当于 x <= y,返回布尔值;
"""
pass
def __long__(self): # real signature unknown; restored from __doc__
"""
x.__long__() 等同于 long(x) 转换为长整数; (Python2特有,Python3已删除)
"""
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
"""
x.__lt__(y) 等同于 x<y 数字小于判断,相当于 x < y,返回布尔值;
"""
pass
def __mod__(self, y): # real signature unknown; restored from __doc__
"""
x.__mod__(y) 等同于 x%y 实现一个“%”操作符代表的取模操作;
"""
pass
def __mul__(self, y): # real signature unknown; restored from __doc__
"""
x.__mul__(y) 等同于 x*y 实现乘法;
"""
pass
def __neg__(self): # real signature unknown; restored from __doc__
"""
x.__neg__() 等同于 -x 数字取负操作;
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
__new__方法接受的参数虽然也是和__init__一样,但__init__是在类实例创建之后调用,而__new__方法正是创建这个类实例的方法;__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple),提供给你一个自定义这些类的实例化过程的途径;
"""
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
"""
x.__ne__(y) 等同于 x!=y 数字不相等判断,相当于x != y,返回布尔值;
"""
pass
def __nonzero__(self): # real signature unknown; restored from __doc__
"""
x.__nonzero__() 等同于 x != 0 数字不等于0判断,相当于x != 0,返回布尔值; (Python2特有,Python3已删除)
"""
pass
def __pos__(self): # real signature unknown; restored from __doc__
"""
x.__pos__() 等同于 +x 数字取正操作;
"""
pass
def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
"""
x.__pow__(y[, z]) 等同于 pow(x, y[, z]) 幂,次方,计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,也可以配合math函数使用;
"""
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
"""
x.__radd__(y) 等同于 y+x 右加法;
"""
pass
def __rdivmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__rdivmod__(y) 等同于 divmod(y, x) 数字相除,将商和余数返回一个数组,相当于 y//x ,返回(商,余数)
"""
pass
def __rdiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rdiv__(y) 等同于 y/x 数字相除,返回商; (Python2特有,Python3已删除)
"""
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,即转换为字符串类型;
"""
pass
def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rfloordiv__(y) 等同于 y//x 用于数字相除取其商;
"""
pass
def __rmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmod__(y) 等同于 y%x 实现一个右“%”操作符代表的取模操作;
"""
pass
def __rmul__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmul__(y) 等同于 y*x 实现右乘法;
"""
pass
def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
"""
y.__rpow__(x[, z]) 等同于 pow(x, y[, z]) 幂,次方,计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,也可以配合math函数使用;
"""
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
"""
x.__rsub__(y) 等同于 y-x 右减法,相当于y减x;
"""
pass
def __rtruediv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rtruediv__(y) 等同于 y/x 右除法,相当于y除以x;
"""
pass
def __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__
"""
float.__setformat__(typestr, fmt) -> None 你最好不要使用这个函数,它的主要存在Python中的的测试套件中; typestr must be 'double' or 'float'. fmt must be one of 'unknown',
'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type.
This affects how floats are converted to and from binary strings.
"""
pass
def __str__(self): # real signature unknown; restored from __doc__
"""
x.__str__() 等同于 str(x) 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式,即转换为字符串类型;
"""
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
"""
x.__sub__(y) 等同于 x-y 减法,相当于x减y;
"""
pass
def __truediv__(self, y): # real signature unknown; restored from __doc__
"""
x.__truediv__(y) 等同于 x/y 除法,相当于x除以y;
"""
pass
def __trunc__(self, *args, **kwargs): # real signature unknown
"""
返回0和x之间最接近x的积分,即返回数值被截取为整形的值;
例如:
>>> x = 1.1
>>> x.__trunc__()
>>> x = 3.6
>>> x.__trunc__()
"""
pass
imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
虚数,无意义;
"""
real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""
实数,无意义;
"""
float
四、str的函数说明
字符串是Python中最常用的数据类型,可以使用引号('或")来创建字符串,同时支撑反斜杠(\)转义特殊字符,Python不支持单字符类型,单字符也在Python也是作为一个字符串使用;
在python中字符串提供的函数如下:
class str(basestring):
"""
str(object='') -> string Python2和Python3的用法一致,在Python2中,主要将参数以字符串形式进行返回,如果参数是字符串,则直接返回;
在Python3中,主要为给定对象创建一个新的字符串对象,如果指定了错误的编码,则必须为对象指定数据缓冲区来处理错误编码;否则,返回the result of object.__str__() (if defined) or repr(object)的报错; 默认的encoding为sys.getdefaultencoding();默认的错误类型为"strict";
"""
def capitalize(self): # real signature unknown; restored from __doc__
"""
S.capitalize() -> string 首字母变大写;
例如:
>>> x = 'abc'
>>> x.capitalize()
'Abc'
"""
return ""
def casefold(self): # real signature unknown; restored from __doc__
"""
S.casefold() -> str 把字符串变成小写,用于不区分大小写的字符串比较,与lower()的区别,在汉语、英语环境下面,继续用lower()没问题;要处理其它语言且存在大小写情况的时候需用casefold(); (Python3新增)
例如:
>>> name = 'Test User'
>>> name.casefold()
'test user'
"""
return ""
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.center(width[, fillchar]) -> string 内容居中,width:总长度;fillchar:空白处填充内容,默认无;
例如:
>>> x = 'abc'
>>> x.center(50,'*')
'***********************abc************************'
"""
return ""
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.count(sub[, start[, end]]) -> int 用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置,即sub参数表示搜索的子字符串;start参数表示字符串开始搜索的位置,默认为第一个字符,第一个字符索引值为0;end参数表示字符串中结束搜索的位置,字符中第一个字符的索引为 0,默认为字符串的最后一个位置;
例如:
>>> x = 'caaaaaaaab'
>>> x.count('a')
8
>>> x.count('a',1,7)
6
"""
return 0
def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__
"""
S.decode([encoding[,errors]]) -> object 以encoding指定的编码格式解码字符串,默认编码为字符串编码;即encoding参数指要使用的编码,如"UTF-8";errors参数指设置不同错误的处理方案,默认为 'strict',意为编码错误引起一个UnicodeError,其他值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值; (Python2特有,Python3已删除)
例如:
>>> str = 'this is string example!'
>>> str = str.encode('base64','strict')
>>> print 'Encoded String: ' + str
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZSE=
>>> print 'Decoded String: ' + str.decode('base64','strict')
Decoded String: this is string example!
"""
return object()
def encode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__
"""
S.encode([encoding[,errors]]) -> object 以encoding指定的编码格式编码字符串,errors参数可以指定不同的错误处理方案;即encoding参数指要使用的编码,如"UTF-8";errors参数指设置不同错误的处理方案,默认为 'strict',意为编码错误引起一个UnicodeError,其他值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过codecs.register_error()注册的任何值;
例如:
>>> str = 'this is string example!'
>>> print 'Encoded String: ' + str.encode('base64','strict')
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZSE=
"""
return object()
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.endswith(suffix[, start[, end]]) -> bool 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False,可选参数"start"与"end"为检索字符串的开始与结束位置;即suffix参数指该参数可以是一个字符串或者是一个元素,start参数指字符串中的开始位置,end参数指字符中结束位置;
例如:
>>> str = 'this is string example!'
>>> print str.endswith('e')
False
>>> print str.endswith('e!')
True
>>> print str.endswith('e!',3)
True
>>> print str.endswith('e!',3,8)
False
"""
return False
def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__
"""
S.expandtabs([tabsize]) -> string 把字符串中的tab符号('\t')转为空格,tab符号('\t')默认的空格数是8,其中tabsize参数指定转换字符串中的tab符号('\t')转为空格的字符数;
例如:
>>> str = 'this is\tstring example!'
>>> print 'Original string: ' + str
Original string: this is string example!
>>> print 'Defualt exapanded tab: ' + str.expandtabs()
Defualt exapanded tab: this is string example!
>>> print 'Double exapanded tab: ' + str.expandtabs(16)
Double exapanded tab: this is string example!
"""
return ""
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.find(sub [,start [,end]]) -> int 检测字符串中是否包含子字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1;即str参数指定检索的字符串;beg参数指开始索引,默认为0;end参数指结束索引,默认为字符串的长度;
例如:
>>> str = 'this is string example!'
>>> str.find('ex')
15
>>> str.find('ex',10)
15
>>> str.find('ex',40)
-1
"""
return 0
def format(self, *args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> string 执行字符串格式化操作,替换字段使用{}分隔,替换字段可以是表示位置的位置或keyword参数名字;其中args指要替换的参数1,kwargs指要替换的参数2;
例如:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
>>> str = 'HOW {0} {1} WORKS'
>>> print(str.format("Python", 3))
HOW Python 3 WORKS
>>> str = 'HOW {soft} {Version} WORKS'
>>> print(str.format(soft = 'Python', Version = 2.7))
HOW Python 2.7 WORKS
"""
pass
def format_map(self, mapping): # real signature unknown; restored from __doc__
"""
S.format_map(mapping) -> str 执行字符串格式化操作,替换字段使用{}分隔,同str.format(**mapping), 除了直接使用mapping,而不复制到一个dict; (Python3新增)
例如:
>>> str = 'HOW {soft} {Version} WORKS'
>>> soft = 'Python'
>>> Version = 2.7
>>> print (str.format_map(vars()))
HOW Python 2.7 WORKS
"""
return ""
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.index(sub [,start [,end]]) -> int 检测字符串中是否包含子字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,该方法与python find()方法一样,只不过如果str不在string中会报一个异常;即str参数指定检索的字符串;beg参数指开始索引,默认为0;end参数指结束索引,默认为字符串的长度;
例如:
>>> str = 'this is string example!'
>>> print str.index('ex')
15
>>> print str.index('ex',10)
15
>>> print str.index('ex',40)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
"""
return 0
def isalnum(self): # real signature unknown; restored from __doc__
"""
S.isalnum() -> bool 检测字符串是否由字母和数字组成,返回布尔值;
例如:
>>> str = 'this2009'
>>> print str.isalnum()
True
>>> str = 'this is string example!'
>>> print str.isalnum()
False
"""
return False
def isalpha(self): # real signature unknown; restored from __doc__
"""
S.isalpha() -> bool 检测字符串是否只由字母组成,返回布尔值,所有字符都是字母则返回 True,否则返回 False;
例如:
>>> str = 'this2009'
>>> print str.isalpha()
False
>>> str = 'this is string example'
>>> print str.isalpha()
False
>>> str = 'this'
>>> print str.isalpha()
True
"""
return False
def isdecimal(self): # real signature unknown; restored from __doc__
"""
S.isdecimal() -> bool 检查字符串是否只包含十进制字符,这种方法只存在于unicode对象,返回布尔值,如果字符串是否只包含十进制字符返回True,否则返回False; (Python3新增)
注:定义一个十进制字符串,只需要在字符串前添加'u'前缀即可;
例如:
>>> str = u'this2009'
>>> print (str.isdecimal())
False
>>> str = u'22342009'
>>> print (str.isdecimal())
True
"""
return False
def isidentifier(self): # real signature unknown; restored from __doc__
"""
S.isidentifier() -> bool
判断字符串是否是合法的标识符,字符串仅包含中文字符合法,实际上这里判断的是变量名是否合法,返回布尔值; (Python3新增)
例如:
>>> str = 'Python3'
>>> print(str.isidentifier())
True
>>> str = '_123'
>>> print(str.isidentifier())
True
>>> str = '123'
>>> print(str.isidentifier())
False
>>> str = ''
>>> print(str.isidentifier())
False
>>> str = '123_'
>>> print(str.isidentifier())
False
>>> str = '#123'
>>> print(str.isidentifier())
False
>>> str = 'a123_'
>>> print(str.isidentifier())
True
>>> #123 = 'a'
...
>>> 123_ = 'a'
File "<stdin>", line 1
123_ = 'a'
^
SyntaxError: invalid token
"""
return False
def isdigit(self): # real signature unknown; restored from __doc__
"""
S.isdigit() -> bool 检测字符串是否只由数字组成,返回布尔值,如果字符串只包含数字则返回 True 否则返回 False;
例如:
>>> str = '123456'
>>> print str.isdigit()
True
>>> str = 'this is string example!'
>>> print str.isdigit()
False
"""
return False
def islower(self): # real signature unknown; restored from __doc__
"""
S.islower() -> bool 检测字符串是否由小写字母组成,返回布尔值,所有字符都是小写,则返回True,否则返回False;
例如:
>>> str = 'this is string example!'
>>> print str.islower()
True
>>> str = 'This is string example!'
>>> print str.islower()
False
"""
return False
def isnumeric(self): # real signature unknown; restored from __doc__
"""
S.isnumeric() -> bool 检测字符串是否只由数字组成,这种方法是只针对unicode对象,返回布尔值,如果字符串中只包含数字字符,则返回True,否则返回False; (Python3新增)
注:定义一个字符串为Unicode,只需要在字符串前添加'u'前缀即可;
例如:
>>> str = u'this2009'
>>> print (str.isnumeric())
False
>>> str = u'22342009'
>>> print (str.isnumeric())
True
"""
return False
def isprintable(self): # real signature unknown; restored from __doc__
"""
S.isprintable() -> bool 判断字符串的所有字符都是可打印字符或字符串为空,返回布尔值; (Python3新增)
例如:
>>> str = 'abc123'
>>> print (str.isprintable())
True
>>> str = '123\t'
>>> print (str.isprintable())
False
>>> str = ''
>>> print (str.isprintable())
True """
return False
def isspace(self): # real signature unknown; restored from __doc__
"""
S.isspace() -> bool 检测字符串是否只由空格组成,返回布尔值,字符串中只包含空格,则返回True,否则返回False;
例如:
>>> str = ' '
>>> print str.isspace()
True
>>> str = 'This is string example!'
>>> print str.isspace()
False
"""
return False
def istitle(self): # real signature unknown; restored from __doc__
"""
S.istitle() -> bool 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写,返回布尔值,如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回True,否则返回False;
例如:
>>> str = 'This Is String Example!'
>>> print (str.istitle())
True
>>> str = 'This Is String example!'
>>> print (str.istitle())
False
"""
return False
def isupper(self): # real signature unknown; restored from __doc__
"""
S.isupper() -> bool 检测字符串中所有的字母是否都为大写,返回布尔值,如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False;
例如:
>>> str = 'THIS IS STRING EXAMPLE!'
>>> print (str.isupper())
True
>>> str = 'This Is String example!'
>>> print (str.istitle())
False
"""
return False
def join(self, iterable): # real signature unknown; restored from __doc__
"""
S.join(iterable) -> string 用于将序列中的元素以指定的字符连接生成一个新的字符串,其中sequence参数指要连接的元素序列;
例如:
>>> str1 = '-'
>>> str2 = ('a','b','c')
>>> print str1.join(str2)
a-b-c
"""
return ""
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.ljust(width[, fillchar]) -> string 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串,如果指定的长度小于原字符串的长度则返回原字符串,其中width参数指指定字符串长度,fillchar参数指填充字符,默认为空格;
>>> str = 'This Is String example!'
>>> print str.ljust(50,'0')
This Is String example!000000000000000000000000000
"""
return ""
def lower(self): # real signature unknown; restored from __doc__
"""
S.lower() -> string 转换字符串中所有大写字符为小写,返回将字符串中所有大写字符转换为小写后生成的字符串;
例如:
>>> str = 'THIS IS STRING EXAMPLE!'
>>> print str.lower()
this is string example!
"""
return ""
def maketrans(self, *args, **kwargs): # real signature unknown
"""
Return a translation table usable for str.translate(). 用于创建字符映射的转换表,并通过str.translate()进行返回,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标;即intab参数指字符串中要替代的字符组成的字符串,outtab参数指相应的映射字符的字符串; (Python3新增)
注:两个字符串的长度必须相同,为一一对应的关系;
例如:
>>> str = 'this is string example!'
>>> intab = 'aeiou'
>>> outtab = '12345'
>>> tarn = str.maketrans(intab,outtab)
>>> print (str.translate(tarn))
th3s 3s str3ng 2x1mpl2!
>>> tarn = str.maketrans('aeiou','12345')
>>> print (str.translate(tarn))
th3s 3s str3ng 2x1mpl2!
"""
pass
def lstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.lstrip([chars]) -> string or unicode 用于截掉字符串左边的空格或指定字符,返回截掉字符串左边的空格或指定字符后生成的新字符串,其中chars参数指指定截取的字符;
例如:
>>> str = ' This Is String example!'
>>> print str.lstrip()
This Is String example!
>>> str = '88888888This Is String example!88888888'
>>> print str.lstrip('8')
This Is String example!88888888
"""
return ""
def partition(self, sep): # real signature unknown; restored from __doc__
"""
S.partition(sep) -> (head, sep, tail) 用来根据指定的分隔符将字符串进行分割,如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串;其中sep参数指指定的分隔符;
例如:
>>> str = 'http://434727.blog.51cto.com/'
>>> print str.partition('://')
('http', '://', '434727.blog.51cto.com/')
"""
pass
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
"""
S.replace(old, new[, count]) -> string 把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数count,则替换不超过count次;
>>> str = 'this is string example! this is really string'
>>> print str.replace('is', 'was')
thwas was string example! thwas was really string
>>> print str.replace('is', 'was',3)
thwas was string example! thwas is really string
"""
return ""
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.rfind(sub [,start [,end]]) -> int 返回字符串最后一次出现的位置,如果没有匹配项则返回-1,其中sub参数指查找的字符串;beg参数指开始查找的位置,默认为0;end参数指结束查找位置,默认为字符串的长度;
例如:
>>> str = 'this is string example!'
>>> print str.rfind('is')
5
>>> print str.rfind('is',0,10)
5
>>> print str.rfind('is',10,0)
-1
"""
return 0
def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.rindex(sub [,start [,end]]) -> int 返回子字符串在字符串中最后出现的位置,如果没有匹配的字符串会报异常,其中sub参数指查找的字符串;beg参数指开始查找的位置,默认为0;end 参数指结束查找位置,默认为字符串的长度;
例如:
>>> str = 'this is string example!'
>>> print str.rindex('is')
5
>>> print str.rindex('is',0,10)
5
>>> print str.rindex('is',10,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
"""
return 0
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.rjust(width[, fillchar]) -> string 返回一个原字符串右对齐,并使用空格填充至长度width的新字符串,如果指定的长度小于字符串的长度则返回原字符串;其中width参数指填充指定字符后中字符串的总长度;fillchar参数指填充的字符,默认为空格;
例如:
>>> str = 'this is string example!'
>>> print str.rjust(50,'0')
000000000000000000000000000this is string example!
"""
return ""
def rpartition(self, sep): # real signature unknown; restored from __doc__
"""
S.rpartition(sep) -> (head, sep, tail) 从后往前查找,返回包含字符串中分隔符之前、分隔符、分隔符之后的子字符串的元组;如果没找到分隔符,返回字符串和两个空字符串;
例如:
>>> str = 'this is string example!'
>>> print str.rpartition('st')
('this is ', 'st', 'ring example!')
>>> print str.rpartition('is')
('this ', 'is', ' string example!')
>>> print str.rpartition('py')
('', '', 'this is string example!')
"""
pass
def rsplit(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__
"""
S.rsplit([sep [,maxsplit]]) -> list of strings 从后往前按照指定的分隔符对字符串进行切片,返回一个列表,其中sep参数指分隔符,默认为空格;maxsplit参数指最多分拆次数;
例如:
>>> str = 'this is string example!'
>>> print str.rsplit()
['this', 'is', 'string', 'example!']
>>> print str.rsplit('st')
['this is ', 'ring example!']
>>> print str.rsplit('is')
['th', ' ', ' string example!']
>>> print str.rsplit('is',1)
['this ', ' string example!']
"""
return []
def rstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.rstrip([chars]) -> string or unicode 删除string字符串末尾的指定字符(默认为空格),返回删除string字符串末尾的指定字符后生成的新字符串,其中chars参数指删除的字符(默认为空格);
例如:
>>> str = ' this is string example! '
>>> print str.rstrip()
this is string example!
>>> str = '88888888this is string example!88888888'
>>> print str.rstrip('8')
88888888this is string example!
"""
return ""
def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__
"""
S.split([sep [,maxsplit]]) -> list of strings 通过指定分隔符对字符串进行切片,如果参数maxsplit有指定值,则仅分隔maxsplit个子字符串;其中sep参数指分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等;maxsplit参数指分割次数;
例如:
>>> str = 'Line1-abcdef \nLine2-abc \nLine4-abcd'
>>> print str.split()
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
>>> print str.split(' ',1)
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
"""
return []
def splitlines(self, keepends=False): # real signature unknown; restored from __doc__
"""
S.splitlines(keepends=False) -> list of strings 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数keepends为 False,不包含换行符,如果为True,则保留换行符,返回一个包含各行作为元素的列表;其中keepends参数指在输出结果里是否去掉换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符;
例如:
>>> str1 = 'ab c\n\nde fg\rkl\r\n'
>>> print str1.splitlines()
['ab c', '', 'de fg', 'kl']
>>> str2 = 'ab c\n\nde fg\rkl\r\n'
>>> print str2.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
"""
return []
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.startswith(prefix[, start[, end]]) -> bool 用于检查字符串是否是以指定子字符串开头,如果是则返回True,否则返回False,如果参数beg和end指定了值,则在指定范围内检查;其中prefix参数指检测的字符串;start参数用于设置字符串检测的起始位置;end参数用于设置字符串检测的结束位置;
例如:
>>> str = 'this is string example!'
>>> print str.startswith('this')
True
>>> print str.startswith('is',2,4)
True
>>> print str.startswith('this',2,4)
False
"""
return False
def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> string or unicode 用于移除字符串头尾指定的字符(默认为空格),返回移除字符串头尾指定的字符生成的新字符串;其中chars参数指移除字符串头尾指定的字符;
例如:
>>> str = '88888888this is string example!88888888'
>>> print str.strip('8')
this is string example!
"""
return ""
def swapcase(self): # real signature unknown; restored from __doc__
"""
S.swapcase() -> string 用于对字符串的大小写字母进行转换,返回大小写字母转换后生成的新字符串;
例如:
>>> str = 'this is string example!'
>>> print str.swapcase()
THIS IS STRING EXAMPLE!
"""
return ""
def title(self): # real signature unknown; restored from __doc__
"""
S.title() -> string 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写;
例如:
>>> str = 'this is string example!'
>>> print str.title()
This Is String Example!
"""
return ""
def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__
"""
S.translate(table [,deletechars]) -> string 根据参数table给出的表(包含256个字符)转换字符串的字符, 要过滤掉的字符放到del参数中,返回翻译后的字符串;其中table参数指翻译表,翻译表是通过maketrans方法转换而来;deletechars参数指字符串中要过滤的字符列表;
例如:
>>> str = 'this is string example!'
>>> intab = 'aeiou'
>>> outtab = '12345'
>>> tarn = str.maketrans(intab,outtab)
>>> print (str.translate(tarn))
th3s 3s str3ng 2x1mpl2!
>>> tarn = str.maketrans('aeiou','12345')
>>> print (str.translate(tarn))
th3s 3s str3ng 2x1mpl2!
"""
return ""
def upper(self): # real signature unknown; restored from __doc__
"""
S.upper() -> string 将字符串中的小写字母转为大写字母,返回小写字母转为大写字母的字符串;
例如:
>>> str = 'this is string example!'
>>> print str.upper()
THIS IS STRING EXAMPLE!
"""
return ""
def zfill(self, width): # real signature unknown; restored from __doc__
"""
S.zfill(width) -> string 返回指定长度的字符串,原字符串右对齐,前面填充0,即width参数指定字符串的长度。原字符串右对齐,前面填充0;
例如:
>>> str = 'this is string example!'
>>> print str.zfill(40)
00000000000000000this is string example!
"""
return ""
def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
"""
(Python2特有,Python3已删除)
"""
pass
def _formatter_parser(self, *args, **kwargs): # real signature unknown
"""
(Python2特有,Python3已删除)
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
"""
x.__add__(y) 等同于 x+y 将两个字符串相加,返回新的字符串;
例如:
>>> x = 'a'
>>> y = 'b'
>>> x.__add__(y)
'ab'
>>> x + y
'ab'
"""
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
"""
x.__contains__(y) 等同于 y in x 字符串包含判断,即判断y是否包含在x中,返回布尔值;
例如:
>>> x = 'a'
>>> y = 'b'
>>> y in x
False
>>> x = 'ab'
>>> y in x
True
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
"""
x.__eq__(y) 等同于 x==y 字符串等同于判断,即判断x是否等于y,返回布尔值;
例如:
>>> x = 'a'
>>> y = 'b'
>>> x == y
False
>>> y = 'a'
>>> x == y
True
"""
pass
def __format__(self, format_spec): # real signature unknown; restored from __doc__
"""
S.__format__(format_spec) -> string 格式化为字符串;
"""
return ""
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
"""
x.__getitem__(y) 等同于 x[y] 返回字符串指定下标的子字符串,下标值需指定并为整数型,否则报错;
例如:
>>> x = 'abc'
>>> y = 1
>>> x.__getitem__(y)
'b'
>>> x[y]
'b'
>>> x.__getitem__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 0
>>> x.__getitem__(1.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not float
"""
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) 等同于 x[i:j] 返回字符串指定范围的子字符串,i参数指开始位置,j参数指结束位置,i,j两个参数必须同时存在,不指定或缺少参数将报错;(Python2特有,Python3已删除)
例如:
>>> x = 'abcdefg'
>>> x.__getslice__(1,4)
'bcd'
>>> x.__getslice__(1,0)
''
>>> x.__getslice__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 2 arguments (0 given)
>>> x.__getslice__(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 2 arguments (1 given)
>>> x[1:4]
'bcd'
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
"""
x.__ge__(y) 等同于 x>=y 字符串大小等于判断,返回布尔值;
例如:
>>> x = 'abc'
>>> y = 'ab'
>>> x >= y
True
>>> y = 'abcd'
>>> x >= y
False
"""
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
"""
x.__gt__(y) 等于 x>y 字符串大于判断,返回布尔值;
例如:
>>> x = 'abc'
>>> y = 'ab'
>>> x > y
True
>>> y = 'abcd'
>>> x > y
False
"""
pass
def __hash__(self): # real signature unknown; restored from __doc__
"""
x.__hash__() 等同于 hash(x) 返回字符串的哈希值;
例如:
>>> x = 'abcd'
>>> x.__hash__()
1540938112
>>> hash(x)
1540938112
"""
pass
def __init__(self, string=''): # known special case of str.__init__
"""
str(object='') -> string 构造方法,执行x = 'abc'时自动调用str函数;
"""
pass
def __len__(self): # real signature unknown; restored from __doc__
"""
x.__len__() 等同于 len(x) 返回字符串的长度;
例如:
>>> x = 'abcd'
>>> x.__len__()
4
>>> len(x)
4
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
"""
迭代对象,返回自己; (Python3新增)
"""
pass
def __le__(self, y): # real signature unknown; restored from __doc__
"""
x.__le__(y) 等同于 x<=y 字符串小于等于判断,返回布尔值;
例如:
>>> x = 'abc'
>>> y = 'abcdef'
>>> x .__le__(y)
True
>>> x <= y
True
>>> y = 'ab'
>>> x <= y
False
"""
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
"""
x.__lt__(y) 等同于 x<y 字符串小于判断,返回布尔值;
>>> x = 'abc'
>>> y = 'abcdef'
>>> x .__lt__(y)
True
>>> x < y
True
>>> y = 'ab'
>>> x < y
False
"""
pass
def __mod__(self, y): # real signature unknown; restored from __doc__
"""
x.__mod__(y) 等同于 x%y
"""
pass
def __mul__(self, n): # real signature unknown; restored from __doc__
"""
x.__mul__(n) 等同于 x*n 字符串乘法,n需为整数,相当于n个字符串相加,新加入的字符串位置在原字符串后;
例如:
>>> x = 'abc'
>>> n = 2
>>> x.__mul__(n)
'abcabc'
>>> x * n
'abcabc'
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
"""
x.__ne__(y) 等同于 x!=y 字符串不等于判断,返回布尔值; """
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,会使用""号将字符串包含起来;
例如:
>>> x = 'abcd'
>>> x.__repr__()
"'abcd'"
>>> repr(x)
"'abcd'"
"""
pass
def __rmod__(self, y): # real signature unknown; restored from __doc__
"""
x.__rmod__(y) 等同于 y%x
"""
pass
def __rmul__(self, n): # real signature unknown; restored from __doc__
"""
x.__rmul__(n) 等同于 n*x 字符串乘法,n需为整数,相当于n个字符串相加,新加入的字符串位置在原字符串前;;
"""
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
S.__sizeof__() -> size of S in memory, in bytes 返回内存中的大小(以字节为单位);
"""
pass
def __str__(self): # real signature unknown; restored from __doc__
"""
x.__str__() <==> str(x) 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式;
"""
pass
str
五、list的函数说明
列表可以完成大多数集合类的数据结构实现,列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套);列表是写在方括号([])之间、用逗号分隔开的元素列表;和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表;
在python中列表提供的函数具体如下:
lass list(object):
"""
list() -> 新的空列表;
list(iterable) -> 从iterable参数中获取值初始化成新的列表;
"""
def append(self, p_object): # real signature unknown; restored from __doc__
"""
L.append(object) 用于在列表末尾添加新的对象,该方法无返回值,但是会修改原来的列表;其中self参数指添加到列表末尾的对象;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist.append( 2009 )
>>> alist
[123, 'xyz', 'zara', 'abc', 2009]
"""
pass
def clear(self): # real signature unknown; restored from __doc__
"""
L.clear() -> None 清空列表; (Python3新增)
例如:
>>> alist = [11,22,33,44]
>>> alist
[11, 22, 33, 44]
>>> alist.clear()
>>> alist
[]
"""
pass def copy(self): # real signature unknown; restored from __doc__
"""
L.copy() -> list 拷贝一个列表,此处是浅拷贝; (Python3新增)
例如:
>>> alist1 = [11,22,33,44]
>>> alist2 = alist.copy()
>>> alist2
[11, 22, 33, 44]
"""
return []
def count(self, value): # real signature unknown; restored from __doc__
"""
L.count(value) -> integer 用于统计某个元素在列表中出现的次数,返回整形,其中obj参数指列表中统计的对象;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc', 123]
>>> print 'Count for 123 : ', alist.count(123)
Count for 123 : 2
>>> print 'Count for zara : ', alist.count('zara')
Count for zara : 1
"""
return 0
def extend(self, iterable): # real signature unknown; restored from __doc__
"""
L.extend(iterable) -- extend 用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),该方法没有返回值,但会在已存在的列表中添加新的列表内容;其中iterable参数指元素列表;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> blist = [2009, 'manni']
>>> alist.extend(blist)
>>> alist
[123, 'xyz', 'zara', 'abc', 2009, 'manni']
"""
pass
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
L.index(value, [start, [stop]]) -> integer 用于从列表中找出某个值第一个匹配项的索引位置,该方法返回查找对象的索引位置,如果没有找到对象则抛出异常;其中value参数指检索的字符串,start参数指检索的起始位置,stop参数指检索的结束位置;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist.index('xyz')
1
>>> alist.index('zara',1)
2
>>> alist.index('zara',1,5)
2
>>> alist.index('zara',1,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'zara' is not in list
"""
return 0
def insert(self, index, p_object): # real signature unknown; restored from __doc__
"""
L.insert(index, object) 用于将指定对象插入列表的指定位置,该方法没有返回值,会直接修改原有列表,其中index参数指插入的位置,object参数指插入的字符串,两个参数需同时指定;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist
[123, 'def', 'xyz', 'zara', 'abc']
>>> alist.insert('def')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)
>>> alist.insert(1,'def')
>>> alist.insert(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)
"""
pass
def pop(self, index=None): # real signature unknown; restored from __doc__
"""
L.pop([index]) -> item 用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,如果列表为空或索引超出范围,则引报错;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist.pop()
'abc'
>>> alist
[123, 'xyz', 'zara']
>>> alist.pop(2)
'zara'
>>> alist
[123, 'xyz']
>>> alist.pop(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> alist = []
>>> alist.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list
"""
pass
def remove(self, value): # real signature unknown; restored from __doc__
"""
L.remove(value) 用于移除列表中某个值的第一个匹配项,该方法没有返回值但是会移除两种中的某个值的第一个匹配项;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc','xyz']
>>> alist.remove('xyz')
>>> alist
[123, 'zara', 'abc', 'xyz']
"""
pass
def reverse(self): # real signature unknown; restored from __doc__
"""
L.reverse() 用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist.reverse()
>>> alist
['abc', 'zara', 'xyz', 123]
"""
pass
def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
"""
L.sort(cmp=None, key=None, reverse=False) 用于对原列表进行排序,如果指定参数,则使用会使用该参数的方法进行排序,该方法没有返回值,但是会对列表的对象进行排序;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> alist.sort()
>>> alist
[123, 'abc', 'xyz', 'zara']
>>> alist.sort(reverse=True)
>>> alist
['zara', 'xyz', 'abc', 123]
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
"""
x.__add__(y) 等同于 x+y 加法,将两个列表值进行相加,并返回新的列表值;
例如:
>>> alist = [123, 'xyz', 'zara', 'abc']
>>> blist = [456, 'wsx', 'edc']
>>> alist.__add__(blist)
[123, 'xyz', 'zara', 'abc', 456, 'wsx', 'edc']
>>> alist + blist
[123, 'xyz', 'zara', 'abc', 456, 'wsx', 'edc']
"""
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
"""
x.__contains__(y) 等同于 y in x 列表包含判断,即判断y是否包含在x中,返回布尔值;
例如:
>>> x = [ 11, 22, 33, 44 ]
>>> y = 11
>>> x.__contains__(y)
True
>>> y in x
True
>>> y = 55
>>> x.__contains__(y)
False
>>> x = [ 11,[ 22, 33], 44]
>>> y = [ 22, 33 ]
>>> x.__contains__(y)
True
"""
pass
def __delitem__(self, y): # real signature unknown; restored from __doc__
"""
x.__delitem__(y) 等同于 del x[y] 用于移除列表中指定下标的一个元素,该方法没有返回值,如果列表为空或索引超出范围,则引报错;
例如:
>>> x = [11,22,33,44]
>>> y = 2
>>> x.__delitem__(y)
>>> x
[11, 22, 44]
>>> del x[y]
>>> x
[11, 22]
>>> x = []
>>> del x[y]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> y = 10
>>> del x[y]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
"""
pass
def __delslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__delslice__(i, j) 等同于 del x[i:j] 用于移除列表中指定下标范围的元素,该方法没有返回值,i参数指开始位置,j参数指结束位置,i,j两个参数必须同时存在,不指定或缺少参数将报错;(Python2特有,Python3已删除)
例如:
>>> x = [11,22,33,44,55]
>>> x.__delslice__(1,3)
>>> x
[11, 44, 55]
>>> x.__delslice__(4,5)
>>> x
[11, 44, 55]
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
"""
x.__eq__(y) 等同于 x==y 列表等同于判断,即判断x是否等于y,返回布尔值;
例如:
>>> x = [11,22,33,44,55]
>>> y = [66,77]
>>> x.__eq__(y)
False
>>> x == y
False
>>> y = [11,22,33,44,55]
>>> x == y
True
"""
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
"""
x.__getitem__(y) 等同于 x[y] 返回列表指定下标的子字符串,并返回子字符串,下标值需指定并为整数型,否则报错;
例如:
>>> x = [11,22,33,44,55]
>>> x.__getitem__(1)
22
"""
pass
def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) 等同于 x[i:j] 返回列表指定范围的子列表,i参数指开始位置,j参数指结束位置,i,j两个参数必须同时存在,不指定或缺少参数将报错;(Python2特有,Python3已删除)
例如:
>>> x = [11,22,33,44,55]
>>> x.__getslice__(1,4)
[22, 33, 44]
>>> x
[11, 22, 33, 44, 55]
>>> x[1:4]
[22, 33, 44]
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
"""
x.__ge__(y) 等同于 x>=y 列表大小等于判断,返回布尔值;
例如:
>>> x = [11,22,33,44,55]
>>> y = [11,22]
>>> x.__ge__(y)
True
>>> x >= y
True
>>> y = [11,22,33,44,55]
>>> x >= y
True
>>> y = [11,22,33,44,55,66]
>>> x >= y
False
"""
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
"""
x.__gt__(y) 等同于 x>y 列表大于判断,返回布尔值;
例如:
>>> x = [11,22,33,44,55]
>>> y = [11,22,33,44]
>>> x.__gt__(y)
True
>>> x > y
True
>>> y = [11,22,33,44,55,66]
>>> x > y
False
"""
pass
def __iadd__(self, y): # real signature unknown; restored from __doc__
"""
x.__iadd__(y) 等同于 x+=y 将第二个个列表加入到第一个列表,即将y的列表值加入x列表,使用x.__iadd__(y)方法会返回改变后的列表,使用x += y只会改变列表不会有返回值;
例如:
>>> x = [11,22,33,44]
>>> y = [55,66]
>>> x.__iadd__(y)
[11, 22, 33, 44, 55, 66]
>>> x
[11, 22, 33, 44, 55, 66]
>>> x += y
>>> x
[11, 22, 33, 44, 55, 66, 55, 66]
"""
pass
def __imul__(self, y): # real signature unknown; restored from __doc__
"""
x.__imul__(y) 等同于 x*=y 列表乘法,y需为整数,相当于y个列表进行相加,并改变原有列表;使用x.__imul__(y)方法会返回改变后的列表,使用x *= y只会改变列表不会有返回值;
例如:
>>> x = [11,22,33,44]
>>> x.__imul__(2)
[11, 22, 33, 44, 11, 22, 33, 44]
>>> x
[11, 22, 33, 44, 11, 22, 33, 44]
>>> x *= 2
>>> x
[11, 22, 33, 44, 11, 22, 33, 44, 11, 22, 33, 44, 11, 22, 33, 44]
"""
pass
def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items 构造方法,执行x = []时自动调用list函数;
"""
pass
def __iter__(self): # real signature unknown; restored from __doc__
"""
x.__iter__() 等同于 iter(x) 迭代对象,返回自己;
"""
pass
def __len__(self): # real signature unknown; restored from __doc__
"""
x.__len__() 等同于 len(x) 返回列表的长度;
例如:
>>> x = [11,22,33,44]
>>> x.__len__()
4
>>> len(x)
4
"""
pass
def __le__(self, y): # real signature unknown; restored from __doc__
"""
x.__le__(y) 等同于 x<=y 列表小于等于判断,返回布尔值;
"""
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
"""
x.__lt__(y) 等同于 x<y
列表小于判断,返回布尔值;
"""
pass
def __mul__(self, n): # real signature unknown; restored from __doc__
"""
x.__mul__(n) 等同于 x*n 列表乘法,n需为整数,相当于n个字符串相加,新加入的字符串位置在原字符串后,不会改变原有列表;
例如:
>>> x = [11,22,33,44]
>>> x.__mul__(2)
[11, 22, 33, 44, 11, 22, 33, 44]
>>> x
[11, 22, 33, 44]
>>> x * 2
[11, 22, 33, 44, 11, 22, 33, 44]
>>> x
[11, 22, 33, 44]
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
"""
x.__ne__(y) 等同于 x!=y 字符串不等于判断,返回布尔值;
"""
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,即转换为字符串格式;
"""
pass
def __reversed__(self): # real signature unknown; restored from __doc__
"""
L.__reversed__() -- return a reverse iterator over the list 返回一个反向迭代器;
"""
pass
def __rmul__(self, n): # real signature unknown; restored from __doc__
"""
x.__rmul__(n) 等同于 n*x 字符串乘法,n需为整数,相当于n个字符串相加,新加入的字符串位置在原字符串前;
"""
pass
def __setitem__(self, i, y): # real signature unknown; restored from __doc__
"""
x.__setitem__(i, y) 等同于 x[i]=y 将x列表指定的i下标值替换为y,该方法直接改变x列表,但没有返回值,
例如:
>>> x = [11,22,33,44]
>>> y = []
>>> x.__setitem__(2,y)
>>> x
[11, 22, [], 44]
>>> y = [55,66]
>>> x[2]= y
>>> x
[11, 22, [55, 66], 44]
"""
pass
def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
"""
x.__setslice__(i, j, y) 等同于 x[i:j]=y 将x列表指定下标范围对应的值,修改为y,i参数指开始位置,j参数指结束位置,i,j两个参数必须同时存在,不指定或缺少参数将报错;(Python2特有,Python3已删除)
例如:
>>> x = [11,22,33,44,55,66]
>>> y = [99,100]
>>> x.__setslice__(1,4,y)
>>> x
[11, 99, 100, 55, 66]
>>> x = [11,22,33,44,55,66]
>>> x[0:3] = y
>>> x
[99, 100, 44, 55, 66]
>>> x = [11,22,33,44,55,66]
>>> x[0:0] = y
>>> x
[99, 100, 11, 22, 33, 44, 55, 66]
"""
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
L.__sizeof__() -- size of L in memory, in bytes 返回内存中的大小(以字节为单位);
"""
pass
__hash__ = None
list
六、元组的函数说明(元组相当于不能修改的列表,其只有只读属性没有修改的属性,使用方法与list函数一致)
元组(tuple)与列表类似,不同之处在于元组的元素不能修改,元组写在小括号(())里,元素之间用逗号隔开;
在python中元组提供的函数如下:
class tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x """
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. (Python2特有,Python3已删除)
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, seq=()): # known special case of tuple.__init__
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass
def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass
def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
def __mul__(self, n): # real signature unknown; restored from __doc__
""" x.__mul__(n) <==> x*n """
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __rmul__(self, n): # real signature unknown; restored from __doc__
""" x.__rmul__(n) <==> n*x """
pass
tuple
七、字典的函数说明
字典(dictionary)是Python中另一个非常有用的内置数据类型,列表是有序的对象结合,字典是无序的对象集合,两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取;
字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合,键(key)必须使用不可变类型,在同一个字典中,键(key)必须是唯一的;
python中字典提供的函数如下:
class dict(object):
"""
dict() -> 新的空字典
dict(mapping) -> 从(key, value)获取值,并初始化的新字典;
dict(iterable) -> 也可通过以下方法初始化新字典:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> 使用name=value方法初始化新字典;
For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
"""
D.clear() -> None.
清空字典;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.clear()
>>> x
{}
"""
pass
def copy(self): # real signature unknown; restored from __doc__
"""
D.copy() -> a shallow copy of D 拷贝一个字典,此处是浅拷贝;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.copy()
>>> y
{'k2': 'v2', 'k1': 'v1'}
"""
pass
@staticmethod # known case
def fromkeys(S, v=None): # real signature unknown; restored from __doc__
"""
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None. 创建并返回一个新字典,以S中的元素做该字典的键,v做该字典中所有键对应的初始值(默认为None);
例如:
>>> x = [ 'k1','k2','k3']
>>> y = {}
>>> y.fromkeys(x,'v1')
{'k3': 'v1', 'k2': 'v1', 'k1': 'v1'}
>>> y
{}
"""
pass
def get(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. 返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.get('k2')
>>> y
'v2'
>>> y = x.get('k3','v3')
>>> y
'v3'
"""
pass
def has_key(self, k): # real signature unknown; restored from __doc__
"""
D.has_key(k) -> True if D has a key k, else False 检查字典是否存在指定的key; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.has_key('k1')
True
>>> x.has_key('v1')
False
>>> x.has_key('k3')
False
"""
return False
def items(self): # real signature unknown; restored from __doc__
"""
D.items() -> list of D's (key, value) pairs, as 2-tuples 返回一个包含所有(key, value)元祖的列表; 例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.items()
>>> y
[('k2', 'v2'), ('k1', 'v1')]
"""
return []
def iteritems(self): # real signature unknown; restored from __doc__
"""
D.iteritems() -> an iterator over the (key, value) items of D 字典项可迭代,方法在需要迭代结果的时候使用最适合,而且它的工作效率非常的高; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.iteritems()
>>> y
<dictionary-itemiterator object at 0x02B0EEA0>
>>> type(y)
<type 'dictionary-itemiterator'>
>>> list(y)
[('k2', 'v2'), ('k1', 'v1')]
"""
pass
def iterkeys(self): # real signature unknown; restored from __doc__
"""
D.iterkeys() -> an iterator over the keys of D key可迭代; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.iterkeys()
>>> y
<dictionary-keyiterator object at 0x030CACF0>
>>> type(y)
<type 'dictionary-keyiterator'>
>>> list(y)
['k2', 'k1']
"""
pass
def itervalues(self): # real signature unknown; restored from __doc__
"""
D.itervalues() -> an iterator over the values of D value可迭代; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.itervalues()
>>> y
<dictionary-valueiterator object at 0x031096F0>
>>> type(y)
<type 'dictionary-valueiterator'>
>>> list(y)
['v2', 'v1']
"""
pass
def keys(self): # real signature unknown; restored from __doc__
"""
D.keys() -> list of D's keys 返回一个包含字典所有key的列表;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.keys()
['k2', 'k1']
"""
return []
def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v 弹出指定key值的元素(因为字典是无序的,所以必须指定key值),会改变原有字典,并返回弹出key的value,如果key不存在,则报错;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.pop('k1')
'v1'
>>> x
{'k2': 'v2'}
>>> x.pop('k3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k3'
"""
pass
def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v) 按照内存顺序删除字典;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.popitem()
('k2', 'v2')
>>> x.popitem()
('k1', 'v1')
>>> x.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'
"""
pass
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.setdefault(k[,d]) -> D.get(k,d) 设置字典key键,如果字典已存在key键,则不改变key键,并返回原有key键的value值,如果字典中不存在Key键,由为它赋值;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.setdefault('k3','v3')
'v3'
>>> x
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
>>> x.setdefault('k1','v3')
'v1'
>>> x
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
"""
pass
def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. 更新字典;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.update({'k3':'v3'})
>>> x
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
"""
pass
def values(self): # real signature unknown; restored from __doc__
"""
D.values() -> list of D's values 获取字典中的值,返回列表;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.values()
['v2', 'v1']
"""
return []
def viewitems(self): # real signature unknown; restored from __doc__
"""
D.viewitems() -> a set-like object providing a view on D's items 为字典D所有对象,提供类似集合的视图; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.viewitems()
dict_items([('k2', 'v2'), ('k1', 'v1')])
"""
pass
def viewkeys(self): # real signature unknown; restored from __doc__
"""
D.viewkeys() -> a set-like object providing a view on D's keys 为字典D的key,提供类型集合的视图; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.viewkeys()
dict_keys(['k2', 'k1'])
"""
pass
def viewvalues(self): # real signature unknown; restored from __doc__
"""
D.viewvalues() -> an object providing a view on D's values 为字典D的values,提供类型集合的视图; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = x.viewvalues()
>>> y
dict_values(['v2', 'v1'])
"""
pass
def __cmp__(self, y): # real signature unknown; restored from __doc__
"""
x.__cmp__(y) 等同于 cmp(x,y) 用于比较两个字典元素,如果两个字典的元素相同返回0,如果字典x大于字典y返回1,如果字典x小于字典y返回-1; (Python2特有,Python3已删除)
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> y = { 'k1':'v1','k2':'v2' }
>>> z = { 'k1':'v3','k2':'v2' }
>>> x.__cmp__(y)
0
>>> x.__cmp__(z)
-1
>>> y = { 'k1':0,'k2':'v2' }
>>> x.__cmp__(y)
1
>>> cmp(x,y)
1
"""
pass
def __contains__(self, k): # real signature unknown; restored from __doc__
"""
D.__contains__(k) -> True if D has a key k, else False 字典包含判断,即判断y是否包含在x中,返回布尔值;
"""
return False
def __delitem__(self, y): # real signature unknown; restored from __doc__
"""
x.__delitem__(y) 等同于 del x[y] 用于移除列表中指定key的元素,该方法没有返回值,如果字典为空或索引超出范围,则引报错;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.__delitem__('k1')
>>> x
{'k2': 'v2'}
>>> x.__delitem__('k3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k3'
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
"""
x.__eq__(y) 等同于 x==y 字典等同于判断,即判断x是否等于y,返回布尔值;
"""
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
"""
x.__getitem__(y) 等同于 x[y] 返回字典指定key的value,并返回value,key值需存在于字典,否则报错;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.__getitem__('k1')
'v1'
>>> x.__getitem__('k3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k3'
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
"""
x.__ge__(y) 等同于 x>=y 字典大于等于判断,返回布尔值;
"""
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
"""
x.__gt__(y) 等同于 x>y 字典大于判断,返回布尔值;
"""
pass
def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
构造方法,执行x = {}时自动调用字典函数;
"""
pass
def __iter__(self): # real signature unknown; restored from __doc__
"""
x.__iter__() 等同于 iter(x) 迭代对象,返回自己;
"""
pass
def __len__(self): # real signature unknown; restored from __doc__
"""
x.__len__() 等同于 len(x) 返回字典的长度;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.__len__()
2
>>> len(x)
2
"""
pass
def __le__(self, y): # real signature unknown; restored from __doc__
"""
x.__le__(y) 等同于 x<=y 字典小于等于判断,返回布尔值;
"""
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
"""
x.__lt__(y) <==> x<y 字典小于判断,返回布尔值;
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
"""
x.__ne__(y) 等同于 x!=y 字典不等于判断,返回布尔值;
"""
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,即转换为字符串格式;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.__repr__()
"{'k2': 'v2', 'k1': 'v1'}"
>>> x
{'k2': 'v2', 'k1': 'v1'}
>>> repr(x)
"{'k2': 'v2', 'k1': 'v1'}"
"""
pass
def __setitem__(self, i, y): # real signature unknown; restored from __doc__
"""
x.__setitem__(i, y) 等同于 x[i]=y 将x字典指定key的value值替换为y,该方法直接改变x字典,但没有返回值;
例如:
>>> x = { 'k1':'v1','k2':'v2' }
>>> x.__setitem__('k1','v3')
>>> x
{'k2': 'v2', 'k1': 'v3'}
"""
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
D.__sizeof__() -> size of D in memory, in bytes 返回内存中的大小(以字节为单位);
"""
pass
__hash__ = None
dict
八、set的函数说明
集合(set)是一个无序不重复元素的序列,基本功能是进行成员关系测试和删除重复元素,可以使用大括号({})或者 set()函数创建集合;
注:创建一个空集合必须用set()而不是{ },因为{ }是用来创建一个空字典;
在python中set提供的函数如下:
class set(object):
"""
set() -> 空的新集合对象;
set(iterable) -> 新的集合对象; Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
""" 在集合中增加元素,如果添加元素已存在于集合,则无效;
例如:
>>> x = set()
>>> x.add('x')
>>> x
set(['x'])
"""
pass
def clear(self, *args, **kwargs): # real signature unknown
""" 清空集合;
例如:
>>> x = set(['k1','k2'])
>>> x
set(['k2', 'k1'])
>>> x.clear()
>>> x
set([])
"""
pass
def copy(self, *args, **kwargs): # real signature unknown
""" 集合的浅拷贝;
例如:
>>> x = set(['k1','k2'])
>>> y = x.copy()
>>> y
set(['k2', 'k1'])
"""
pass
def difference(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的不同(差集),并生成一个新的集合;即获取x.difference(y)的差集,相当于获取x多余y的集合值;
如果x包含于y,则获取空值;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> s3 = x.difference(y)
>>> s3
set(['c'])
>>> s4 = y.difference(x)
>>> s4
set([])
"""
pass
def difference_update(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的不同(差集),改变原来的集合;即获取x.difference_update(y)的差集,相当于获取x多余y的集合值,并重写进x;
如果x包含于y,则获取空值,并重写进x;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.difference_update(y)
>>> x
set(['c'])
>>> y
set(['a', 'b'])
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> y.difference_update(x)
>>> y
set([])
>>> x
set(['a', 'c', 'b'])
"""
pass
def discard(self, *args, **kwargs): # real signature unknown
""" 移除集合中的一个指定元素,如果这个元素不存在,则不变;
例如:
>>> x = set(['a','b','c'])
>>> x.discard('a')
>>> x
set(['c', 'b'])
>>> x.discard('d')
>>> x
set(['c', 'b'])
"""
pass
def intersection(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的交集,生成一个新的集合;即获取x.intersection(y)的交集,相当于获取x与y相等的那部分集合值;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.intersection(y)
set(['a', 'b'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['a', 'b'])
"""
pass
def intersection_update(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的交集,改变原来的集合; 即获取x.intersection_update(y)的交集,相当于获取x与y相等的那部分集合值,并重写进x;
如果x包含于y,则无变化;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.intersection_update(y)
>>> x
set(['a', 'b'])
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> y.intersection_update(x)
>>> y
set(['a', 'b'])
>>> x
set(['a', 'c', 'b'])
"""
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" 判断两个集合是否没有交集,如果是返回True,如果不是返回False;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.isdisjoint(y)
False
>>> y = set(['d'])
>>> x.isdisjoint(y)
True
"""
pass
def issubset(self, *args, **kwargs): # real signature unknown
""" 判断一个集合是否是另一个集合的子集; 即x.issubset(y),相当于判断x是否y的子集;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.issubset(y)
False
>>> y.issubset(x)
True
"""
pass
def issuperset(self, *args, **kwargs): # real signature unknown
""" 判断一个集合是否包含另一个集合;即x.issuperset(y),相当于判断x是否包含y;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.issuperset(y)
True
>>> y.issuperset(x)
False
"""
pass
def pop(self, *args, **kwargs): # real signature unknown
""" 删除并返回任意设置的元素,如果集合为空,则引发KeyError;
例如:
>>> x = set(['a','b','c'])
>>> x.pop()
'a'
>>> x.pop()
'c'
>>> x.pop()
'b'
>>> x.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop from an empty set'
"""
pass
def remove(self, *args, **kwargs): # real signature unknown
""" 移除集合中指定的元素,如果集合为空或指定的元素不存在,则引发KeyError;
例如:
>>> x = set(['a','b','c'])
>>> x.remove('b')
>>> x
set(['a', 'c'])
>>> x.remove('d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'd'
"""
pass
def symmetric_difference(self, *args, **kwargs): # real signature unknown
""" 把两个集合中的不同元素,即差集,放到一个新的集合中;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.symmetric_difference(y)
set(['a', 'b', 'd'])
"""
pass
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" 两个集合不相同的元素,即差集,并改变原集合;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.symmetric_difference_update(y)
>>> x
set(['a', 'b', 'd'])
>>> y
set(['c', 'd'])
"""
pass
def union(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的并集,并生成一个新的集合;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.union(y)
set(['a', 'c', 'b', 'd'])
>>> x
set(['a', 'c', 'b'])
"""
pass
def update(self, *args, **kwargs): # real signature unknown
""" 获取两个集合的并集,并生改变原集合;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.update(y)
>>> x
set(['a', 'c', 'b', 'd'])
>>> y
set(['c', 'd'])
"""
pass
def __and__(self, y): # real signature unknown; restored from __doc__
"""
x.__and__(y) 等同于 x&y 集合与操作,相当于获取两个集合相同值,即交集,并进行返回;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__and__(y)
set(['c'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['c', 'd'])
>>> x = set(['a','b','c'])
>>> y = set(['b','c'])
>>> x & y
set(['c', 'b'])
"""
pass
def __cmp__(self, y): # real signature unknown; restored from __doc__
"""
x.__cmp__(y) 等同于 cmp(x,y) 无意义 (Python2特有,Python3已删除)
"""
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
"""
x.__contains__(y) 等同于 y in x 集合包含判断,即判断y是否包含在x中,返回布尔值;
例如:
>>> x = set(['a','b','c'])
>>> y = 'a'
>>> x.__contains__(y)
True
>>> y in x
True
>>> y = 'd'
>>> x.__contains__(y)
False
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
"""
x.__eq__(y) 等同于 x==y 集合等同于判断,即判断x是否等于y,返回布尔值;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b','c'])
>>> x.__eq__(y)
True
>>> x == y
True
>>> y = set(['a','b'])
>>> x == y
False
"""
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""
x.__getattribute__('name') 等同于 x.name
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
"""
x.__ge__(y) 等同于 x>=y 集合大小等于判断,返回布尔值;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.__ge__(y)
True
>>> x >= y
True
>>> y = set(['a','b','c'])
>>> x >= y
True
>>> y = set(['a','b','c','d'])
>>> x >= y
False
"""
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
"""
x.__gt__(y) 等同于 x>y 集合大于判断,返回布尔值;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['a','b'])
>>> x.__gt__(y)
True
>>> x > y
True
>>> y = set(['a','b','c'])
>>> x > y
False
"""
pass
def __iand__(self, y): # real signature unknown; restored from __doc__
"""
x.__iand__(y) 等同于 x&=y 集合与操作,相当于获取两个集合相同值,即交集,并进行返回及修改集合x;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__iand__(y)
set(['c'])
>>> x
set(['c'])
>>> y
set(['c', 'd'])
>>> x = set(['a','b','c'])
"""
pass
def __init__(self, seq=()): # known special case of set.__init__
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
# (copied from class doc) 构造方法,执行x = set()时自动调用集合函数;
"""
pass
def __ior__(self, y): # real signature unknown; restored from __doc__
"""
x.__ior__(y) 等同于 x|=y 获取两个集合的并集,并进行返回及改变原集合;
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__ior__(y)
set(['a', 'c', 'b', 'd'])
>>> x
set(['a', 'c', 'b', 'd'])
>>> y
set(['c', 'd'])
>>> x = set(['a','b','c'])
>>> x |= y
set(['a', 'c', 'b', 'd'])
>>> x
set(['a', 'c', 'b', 'd'])
>>> y
set(['c', 'd'])
"""
pass
def __isub__(self, y): # real signature unknown; restored from __doc__
"""
x.__isub__(y) 等同于 x-=y 集合减法,即x集合减去y集合,并进行结果返回及修改x集合;
例如:
>>> x = set(['a','b','c','d'])
>>> y = set(['c','d'])
>>> x.__isub__(y)
set(['a', 'b'])
>>> x
set(['a', 'b'])
>>> y
set(['c', 'd'])
"""
pass
def __iter__(self): # real signature unknown; restored from __doc__
"""
x.__iter__() 等同于 iter(x) 迭代对象,返回自己;
"""
pass
def __ixor__(self, y): # real signature unknown; restored from __doc__
"""
x.__ixor__(y) 等同于 x^=y 把两个集合中的不同元素(对称差集)放到一个原集合中,即把x与y集合的不同元素,放置到x集合中;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__ixor__(y)
set(['a', 'b', 'd'])
>>> x
set(['a', 'b', 'd'])
>>> y
set(['c', 'd'])
>>> x = set(['a','b','c'])
>>> x ^= y
set(['a', 'b', 'd'])
>>> x
set(['a', 'b', 'd'])
>>> y
set(['c', 'd'])
"""
pass
def __len__(self): # real signature unknown; restored from __doc__
"""
x.__len__() 等同于 len(x) 返回集合长度;
"""
pass
def __le__(self, y): # real signature unknown; restored from __doc__
"""
x.__le__(y) 等同于 x<=y 集合小于判断,返回布尔值;
"""
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
"""
x.__lt__(y) 等同于 x<y 集合小于判断,返回布尔值;
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
"""
T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
"""
x.__ne__(y) 等同于 x!=y 集合不等于判断,返回布尔值;
"""
pass
def __or__(self, y): # real signature unknown; restored from __doc__
"""
x.__or__(y) 等同于 x|y 获取两个集合的并集,并生成一个新的集合;
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__or__(y)
set(['a', 'c', 'b', 'd'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['c', 'd'])
>>> y | x
set(['a', 'c', 'b', 'd'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['c', 'd'])
"""
pass
def __rand__(self, y): # real signature unknown; restored from __doc__
"""
x.__rand__(y) 等同于 y&x 获取两个集合的交集,生成一个新的集合;
例如:
>>> x = set(['a','b'])
>>> y = set(['a','b','c'])
>>> x.__rand__(y)
set(['a', 'b'])
>>> y & x
set(['a', 'b'])
"""
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
"""
Return state information for pickling.
"""
pass
def __repr__(self): # real signature unknown; restored from __doc__
"""
x.__repr__() 等同于 repr(x) 转化为解释器可读取的形式,即转换为字符串格式;
"""
pass
def __ror__(self, y): # real signature unknown; restored from __doc__
"""
x.__ror__(y) 等同于 y|x 获取两个集合的并集,并生成一个新的集合;;
例如:
>>> x = set(['a','b'])
>>> y = set(['a','b','c'])
>>> x.__ror__(y)
set(['a', 'c', 'b'])
>>> x
set(['a', 'b'])
>>> y
set(['a', 'c', 'b'])
>>> y | x
set(['a', 'c', 'b'])
"""
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
"""
x.__rsub__(y) 等同于 y-x 获取两个集合的不同(差集),并生成一个新的集合(项在y中,但不在x中);
例如:
>>> x = set(['a','b'])
>>> y = set(['a','b','c'])
>>> x.__rsub__(y)
set(['c'])
>>> y.__rsub__(x)
set([])
"""
pass
def __rxor__(self, y): # real signature unknown; restored from __doc__
"""
x.__rxor__(y) 等同于 y^x 获取两个集合的不同(差集),并生成一个新的集合
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__rxor__(y)
set(['a', 'b', 'd'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['c', 'd'])
>>> y ^ x
set(['a', 'b', 'd'])
"""
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
S.__sizeof__() -> size of S in memory, in bytes
返回内存中的大小(以字节为单位);
"""
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
"""
x.__sub__(y) 等同于 x-y 获取两个集合的不同(差集),并生成一个新的集合(项在x中,但不在y中);
例如:
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__sub__(y)
set(['a', 'b'])
>>> x
set(['a', 'c', 'b'])
>>> y
set(['c', 'd'])
>>> y - x
set(['d'])
"""
pass
def __xor__(self, y): # real signature unknown; restored from __doc__
"""
x.__xor__(y) 等同于 x^y 两个集合不相同的元素(差集),并返回结果;
>>> x = set(['a','b','c'])
>>> y = set(['c','d'])
>>> x.__xor__(y)
set(['a', 'b', 'd'])
>>> x
set(['a', 'c', 'b'])
>>> x
set(['c', 'd'])
>>> y ^ x
set(['a', 'b', 'd'])
"""
pass
__hash__ = None
set
九、collection系列函数说明
collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是:
OrderedDict类:排序字典,是字典的子类。引入自2.7;
namedtuple()函数:命名元组,是一个工厂函数。引入自2.6;
Counter类:为hashable对象计数,是字典的子类。引入自2.7;
deque:双向队列。引入自2.4;
defaultdict:使用工厂函数创建字典,使不用考虑缺失的字典键。引入自2.5;
使用的时候需要用import导入collections模块;
1、计数器(counter)函数说明
Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数);
注:具备字典的所有功能 + 自己的功能;
########################################################################
### Counter
########################################################################
def _count_elements(mapping, iterable):
'Tally elements from the iterable.'
mapping_get = mapping.get
for elem in iterable:
mapping[elem] = mapping_get(elem, 0) + 1
try: # Load C helper function if available
from _collections import _count_elements
except ImportError:
pass
'''
如果C的帮助函数可用的话,则加载; (Python3新增)
'''
class Counter(dict):
'''
Dict子类用于计算哈希项,有时称为包或多集,元素存储为字典键,它们的计数存储为字典值;
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a'] # count of letter 'a'
5
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element's count
>>> c['a'] # now there are seven 'a'
7
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b'
0
>>> d = Counter('simsalabim') # make another counter
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a'
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
'''
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3
def __init__(*args, **kwds):
'''
创建一个新的空Counter对象,可对输入可迭代元素进行计数,也可以对另外一个元素映射过来的元素进行计数;
主要是先调用父类(dict)的初始化,然后使用update函数来更新参数;
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0
'''
对于不存在的元素,返回计数器为0;
总结一下就是dict本身没有这个方法,但是如果当前类为dict的子类的话;
会在缺失的情况下查看有没有实现__missing__方法,如果有的话,就返回__miss__方法的值;
所以Counter作为dict的子类实现了__missing__方法,在缺失的时候返回0;
这也就是为什么在Counter类中,如果找不到key,会返回0而不是产生一个KeyError;
例如:
>>> import collections
>>> c = collections.Counter('abbcc')
>>> c['a']
2
>>> c['b']
2
>>> c['d']
0
'''
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
'''
数量从大到写排列,返回一个TopN列表,如果n没有被指定,则返回所有元素;
当多个元素计数值相同时,按照字母序排列;
例如:
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
'''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.items()))
'''
返回一个迭代器。元素被重复了多少次,在该迭代器中就包含多少个该元素;
所有元素按照字母序排序,个数小于1的元素不被包含;
注:此处非所有元素集合,而是包含所有元素集合的迭代器;
例如:
>>> import collections
>>> c = collections.Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
'''
# Override dict methods where necessary
@classmethod
def fromkeys(cls, iterable, v=None):
# There is no equivalent method for counters because setting v=1
# means that no element can have a count greater than one.
raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
'''
未实现的类方法;
'''
def update(*args, **kwds):
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4
'''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts.
if not args:
raise TypeError("descriptor 'update' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for elem, count in iterable.items():
self[elem] = count + self_get(elem, 0)
else:
super(Counter, self).update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable)
if kwds:
self.update(kwds)
'''
更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一;
例如:
>>> from collections import Counter
>>> c = Counter('which')
>>> c
Counter({'h': 2, 'i': 1, 'c': 1, 'w': 1})
>>> c.update('witch')
>>> c
Counter({'h': 3, 'i': 2, 'c': 2, 'w': 2, 't': 1})
>>> c['h']
3
>>> d = Counter('watch')
>>> d
Counter({'a': 1, 'h': 1, 'c': 1, 't': 1, 'w': 1})
>>> c.update(d)
>>> c
Counter({'h': 4, 'c': 3, 'w': 3, 'i': 2, 't': 2, 'a': 1})
>>> c['h']
4
'''
def subtract(*args, **kwds):
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.subtract('witch') # subtract elements from another iterable
>>> c.subtract(Counter('watch')) # subtract elements from another counter
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
'''
if not args:
raise TypeError("descriptor 'subtract' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
self_get = self.get
if isinstance(iterable, Mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, 0) - count
else:
for elem in iterable:
self[elem] = self_get(elem, 0) - 1
if kwds:
self.subtract(kwds)
'''
相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量;
例如:
>>> from collections import Counter
>>> c = Counter('which')
>>> c.subtract('witch')
>>> c
Counter({'h': 1, 'i': 0, 'c': 0, 'w': 0, 't': -1})
>>> c['h']
1
>>> d = Counter('watch')
>>> c.subtract(d)
>>> c['a']
-1
'''
def copy(self):
'Return a shallow copy.'
return self.__class__(self)
'''
浅拷贝;
例如:
>>> from collections import Counter
>>> c = Counter('abcdcba')
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
>>> d = c.copy()
>>> d
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
'''
def __reduce__(self):
return self.__class__, (dict(self),)
'''
返回一个元组(类型,元组);
例如:
>>> c = Counter('abcdcba')
>>> c.__reduce__()
(<class 'collections.Counter'>, ({'a': 2, 'c': 2, 'b': 2, 'd': 1},))
>>> d = c.__reduce__()
>>> type(d)
<type 'tuple'>
'''
def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem in self:
super().__delitem__(elem)
'''
删除元素,等同于del;
本质上就是一个不抛出KeyError的dict类的__delitem()__;
>>> c = Counter('abcdcba')
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
>>> c['b'] = 0
>>> c
Counter({'a': 2, 'c': 2, 'd': 1, 'b': 0})
>>> c.__delitem__('a')
>>> c
Counter({'c': 2, 'd': 1, 'b': 0})
>>> del c['b']
>>> c
Counter({'c': 2, 'd': 1})
'''
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
try:
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
except TypeError:
# handle case where values are not orderable
return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
'''
如果没有对象就返回类的名字,否则返回类的名字并且返回利用most_common()方法得到类中的信息;
例如:
>>> from collections import Counter
>>> c = Counter('aabbccdd')
>>> c.__repr__()
"Counter({'a': 2, 'c': 2, 'b': 2, 'd': 2})"
>>> c = Counter()
>>> c.__repr__()
'Counter()'
'''
# Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19
# and at http://en.wikipedia.org/wiki/Multiset
#
# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter()
def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
'''
加法运算,相当于+,结果中只会出现计数count大于0的元素;
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c2 = Counter({'b':2,'c':1})
>>> c1.__add__(c2)
Counter({'c': 4, 'b': 3})
>>> c1 + c2
Counter({'c': 4, 'b': 3})
'''
def __sub__(self, other):
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count - other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < 0:
result[elem] = 0 - count
return result
'''
减法运算,相当于-,结果中只会出现计数count大于0的元素;
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c2 = Counter({'b':2,'c':1})
>>> c1.__sub__(c2)
Counter({'c': 2})
>>> c1 - c2
Counter({'c': 2})
'''
def __or__(self, other):
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
'''
并集运算,相当于|,结果中只会出现计数count大于0的元素及主要是选相同元素中count最大的一个;
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c2 = Counter({'b':2,'c':1})
>>> c1.__or__(c2)
Counter({'c': 3, 'b': 2})
>>> c1 | c2
Counter({'c': 3, 'b': 2})
'''
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > 0:
result[elem] = newcount
return result
'''
交集运算,相当于&,结果中只会出现计数count大于0的元素及主要是选相同元素中count最小的一个;
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c2 = Counter({'b':2,'c':1})
>>> c1.__and__(c2)
Counter({'c': 1, 'b': 1})
>>> c1 & c2
Counter({'c': 1, 'b': 1})
'''
def __pos__(self):
'Adds an empty counter, effectively stripping negative and zero counts'
result = Counter()
for elem, count in self.items():
if count > 0:
result[elem] = count
return result
'''
用于清除值为负数和零的计数; (Python3新增)
例如:
>>> from collections import Counter
>>> c1 = Counter({'a':0,'b':1,'c':-3})
>>> c1.__pos__()
Counter({'b': 1})
'''
def __neg__(self):
'''Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts.
'''
result = Counter()
for elem, count in self.items():
if count < 0:
result[elem] = 0 - count
return result
'''
用于清除值为正数或者零的计数,并将值为负数的计数,转换为正数; (Python3新增)
例如:
>>> c1 = Counter({'a':0,'b':1,'c':-3})
>>> c1.__neg__()
Counter({'c': 3})
'''
def _keep_positive(self):
'''Internal method to strip elements with a negative or zero count'''
nonpositive = [elem for elem, count in self.items() if not count > 0]
for elem in nonpositive:
del self[elem]
return self
def __iadd__(self, other):
'''Inplace add from another counter, keeping only positive counts.
>>> c = Counter('abbb')
>>> c += Counter('bcc')
>>> c
Counter({'b': 4, 'c': 2, 'a': 1})
'''
for elem, count in other.items():
self[elem] += count
return self._keep_positive()
'''
自加,相当于+=,结果中只会出现计数count大于0的元素; (Python3新增)
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c1 += Counter({'b':2,'c':1})
>>> c1
Counter({'c': 4, 'b': 3})
'''
def __isub__(self, other):
'''Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
'''
for elem, count in other.items():
self[elem] -= count
return self._keep_positive()
'''
自减,相当于-=,结果中只会出现计数count大于0的元素; (Python3新增)
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c1 -= Counter({'b':1,'c':1})
>>> c1
Counter({'c': 2})
'''
def __ior__(self, other):
'''Inplace union is the maximum of value from either counter.
>>> c = Counter('abbb')
>>> c |= Counter('bcc')
>>> c
Counter({'b': 3, 'c': 2, 'a': 1})
'''
for elem, other_count in other.items():
count = self[elem]
if other_count > count:
self[elem] = other_count
return self._keep_positive()
'''
自并集运算,相当于|=,结果中只会出现计数count大于0的元素及主要是选相同元素中count最大的一个; (Python3新增)
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c1 |= Counter({'b':1,'d':2})
>>> c1
Counter({'c': 3, 'd': 2, 'b': 1})
'''
def __iand__(self, other):
'''Inplace intersection is the minimum of corresponding counts.
>>> c = Counter('abbb')
>>> c &= Counter('bcc')
>>> c
Counter({'b': 1})
'''
for elem, count in self.items():
other_count = other[elem]
if other_count < count:
self[elem] = other_count
return self._keep_positive()
'''
自交集运算,相当于&=,结果中只会出现计数count大于0的元素及主要是选相同元素中count最小的一个; (Python3新增)
例如:
>>> c1 = Counter({'a':0,'b':1,'c':3})
>>> c1 &= Counter({'b':1,'d':2})
>>> c1
Counter({'b': 1})
'''
Counter
2、有序字典(OrderdDict)函数说明
OrderdDict是对字典类型的补充,他记住了字典元素添加的顺序;
################################################################################
### OrderedDict
################################################################################
class _OrderedDictKeysView(KeysView):
def __reversed__(self):
yield from reversed(self._mapping)
'''
用于被OrderedDict的keys方法调用; (Python3新增)
'''
class _OrderedDictItemsView(ItemsView):
def __reversed__(self):
for key in reversed(self._mapping):
yield (key, self._mapping[key])
'''
用于被OrderedDict的items方法调用; (Python3新增)
'''
class _OrderedDictValuesView(ValuesView):
def __reversed__(self):
for key in reversed(self._mapping):
yield self._mapping[key]
'''
用于被OrderedDict的values方法调用; (Python3新增)
'''
class _Link(object):
__slots__ = 'prev', 'next', 'key', '__weakref__'
'''
未实现的方法; (Python3新增)
'''
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
# The prev links are weakref proxies (to prevent circular references).
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict.
'''
记住插入顺序的字典;
继承的dict的keys和values;
继承的dict提供__getitem__,__len__,__contains__和get方法;
其余的方法都按顺序执行;
所有方法的执行时间都和普通字典一样;
引用在OrderedDict删除键时消失;
'''
def __init__(*args, **kwds):
'''
初始化有序字典。签名与常规字典相同,但不推荐使用关键字参数,因为插入顺序;
'''
if not args:
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
'''
od.__setitem__(i, y)等同于od[i]=y;
设置的新项目会在链接列表的末尾创建一个新链接,并且继承的字典使用新的键/值对进行更新方法;
例如:
>>> from collections import OrderedDict
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> od.__setitem__('k4','v4')
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
>>> od['k5'] = 'v5'
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4'), ('k5', 'v5')])
'''
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
link.prev = None
link.next = None
'''
od.__delitem__(y)等同于del od[y];
使用self.__map找到现有项目并进行删除,删除后通过更新前导节点和后继节点的链接来覆盖删除的链接;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od.__delitem__('k1')
>>> od
OrderedDict([('k2', 'v2'), ('k3', 'v3')])
>>> del od['k2']
>>> od
OrderedDict([('k3', 'v3')])
'''
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root.next
while curr is not root:
yield curr.key
curr = curr.next
'''
od.__iter__()等同于iter(od)
按顺序遍历字典链表;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> od.__iter__()
<odict_iterator object at 0x0000027FF1D11F10>
>>> nod = od.__iter__()
>>> type(nod)
<class 'odict_iterator'>
>>> iter(od)
<odict_iterator object at 0x0000027FF1D11F10>
'''
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root.prev
while curr is not root:
yield curr.key
curr = curr.prev
'''
od.__reversed__()等同于reversed(od)
以相反的顺序遍历字典链表,及返回一个反向迭代器;
'''
def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self)
'''
删除所有项目;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> od.clear()
>>> od
OrderedDict()
'''
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value
'''
按照先进先出删除key,value,并返回删除key和value;
如果参数last默认值True,表示以LIFO顺序(先进先出)进行删除和返回;
如果last为Flase,则以FIFO顺序(后进先出)进行删除和返回;
也可直接指定key的索引值进行删除;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.popitem()
('k4', 'v4')
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> od.popitem(last = False)
('k1', 'v1')
>>> od
OrderedDict([('k2', 'v2'), ('k3', 'v3')])
>>> od.popitem(0)
('k2', 'v2')
>>> od
OrderedDict([('k3', 'v3')])
'''
def move_to_end(self, key, last=True):
'''Move an existing element to the end (or beginning if last==False).
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key).
'''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
last.next = root.prev = link
else:
first = root.next
link.prev = root
link.next = first
root.next = first.prev = link
'''
移动现有元素,等同于od[key] = od.pop(key); (Python3新增)
当last参数为True(默认值)时,将现有元素移动到结尾;
如果last参数为False时,则将现有元素移动开头;
如果元素不存在,则引发KetError;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.move_to_end('k1')
>>> od
OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4'), ('k1', 'v1')])
>>> od.move_to_end('k4',last = False)
>>> od
OrderedDict([('k4', 'v4'), ('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
>>> od['k2'] = od.pop('k2')
>>> od
OrderedDict([('k4', 'v4'), ('k3', 'v3'), ('k1', 'v1'), ('k2', 'v2')])
'''
def __sizeof__(self):
sizeof = _sys.getsizeof
n = len(self) + 1 # number of links including root
size = sizeof(self.__dict__) # instance dictionary
size += sizeof(self.__map) * 2 # internal dict and inherited dict
size += sizeof(self.__hardroot) * n # link objects
size += sizeof(self.__root) * n # proxy objects
return size
'''
返回内存中的大小(以字节为单位); (Python3新增)
'''
update = __update = MutableMapping.update
def keys(self):
"D.keys() -> a set-like object providing a view on D's keys"
return _OrderedDictKeysView(self)
'''
返回一个包含key的类似集合的对象;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.keys()
odict_keys(['k1', 'k2', 'k3', 'k4'])
'''
def items(self):
"D.items() -> a set-like object providing a view on D's items"
return _OrderedDictItemsView(self)
'''
返回一个包含所有(key, value)类似集合的对象;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.items()
odict_items([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
'''
def values(self):
"D.values() -> an object providing a view on D's values"
return _OrderedDictValuesView(self)
'''
返回一个包含value的类似集合的对象;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.values()
odict_values(['v1', 'v2', 'v3', 'v4'])
'''
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
'''
key可迭代; (Python2特有,Python3已删除)
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.iterkeys()
<generator object __iter__ at 0x02E653A0>
>>> nod = od.iterkeys()
>>> type(nod)
<type 'generator'>
>>> nod.next()
'k3'
>>> nod.next()
'k2'
>>> nod.next()
'k1'
'''
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
'''
value可迭代; (Python2特有,Python3已删除)
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>>od.itervalues()
<generator object itervalues at 0x02E654E0>
>>> nod = od.itervalues()
>>> type(nod)
<type 'generator'>
>>> nod.next()
'v3'
>>> nod.next()
'v2'
>>> nod.next()
'v1'
'''
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) pairs in od'
for k in self:
yield (k, self[k])
'''
key, value可迭代; (Python2特有,Python3已删除)
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3','k4':'v4'})
>>> od.iteritems()
<generator object iteritems at 0x02E654E0>
>>> nod = od.iteritems()
>>> nod.next()
('k3', 'v3')
>>> nod.next()
('k2', 'v2')
>>> nod.next()
('k1', 'v1')
'''
__ne__ = MutableMapping.__ne__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
'''
删除指定的键并返回相应的值,如果设置了d参数,并未找到key时,则返回d参数,否则返回KeyError;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od.pop('k1')
'v1'
>>> od
OrderedDict([('k2', 'v2'), ('k3', 'v3')])
>>> od.pop('k4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k4'
>>> od.pop('k4','k4_no_found')
'k4_no_found'
'''
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
'''
设置key键,如果已存在key键,则不改变key键,并返回原有key键的value值,如果不存在Key键,由为它赋值;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od.setdefault('k3','v4')
'v3'
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> od.setdefault('k4','v4')
'v4'
>>> od
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
'''
@_recursive_repr()
def __repr__(self):
'od.__repr__() <==> repr(od)'
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
'''
od.__repr__()等同于repr(od)
转化为解释器可读取的形式,即转换为字符串格式;
例如:
>>> od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> nod = od.__repr__()
>>> nod
"OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])"
>>> type(nod)
<class 'str'>
'''
def __reduce__(self):
'Return state information for pickling'
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
return self.__class__, (), inst_dict or None, None, iter(self.items())
'''
返回pickling状态的信息;
例如:
od = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> nod = od.__reduce__()
>>> nod
(<class 'collections.OrderedDict'>, (), None, None, <odict_iterator object at 0x0000027FF1D11F10>)
>>> type(nod)
<class 'tuple'>
'''
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
'''
浅拷贝;
'''
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
'''
获取S的keys,并生成新字典 如果v参数未指定,则值默认为None;
例如:
>>> od1 = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od2 = OrderedDict({'k4':'v4','k5':'v5','k6':'v6'})
>>> od2.fromkeys(od1,'v')
OrderedDict([('k1', 'v'), ('k2', 'v'), ('k3', 'v')])
>>> od2
OrderedDict([('k4', 'v4'), ('k5', 'v5'), ('k6', 'v6')])
>>> od2.fromkeys(od1)
OrderedDict([('k1', None), ('k2', None), ('k3', None)])
'''
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(map(_eq, self, other))
return dict.__eq__(self, other)
'''
od.__eq__(y) 等同于 od==y
有序字典等同于判断,即判断od是否等于y,返回布尔值;
例如:
>>> od1 = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od2 = OrderedDict({'k4':'v4','k5':'v5','k6':'v6'})
>>> od1.__eq__(od2)
False
>>> od2 = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od1.__eq__(od2)
True
>>> od1 == od2
True
'''
def __ne__(self, other):
'od.__ne__(y) <==> od!=y'
return not self == other
'''
有序字典等不同于判断,即判断od是否不等于y,返回布尔值;
例如:
>>> od1 = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od2 = OrderedDict({'k4':'v4','k5':'v5','k6':'v6'})
>>> od1.__ne__(od2)
True
>>> od1 != od2
True
>>> od2 = OrderedDict({'k1':'v1','k2':'v2','k3':'v3'})
>>> od1.__ne__(od2)
False
'''
# -- the following methods support python 3.x style dictionary views --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
'''
返回一个包含key的类似集合的对象; (Python2特有,Python3已删除)
'''
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
'''
返回一个包含value的类似集合的对象; (Python2特有,Python3已删除)
'''
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
'''
返回一个包含所有(key, value)类似集合的对象; (Python2特有,Python3已删除)
'''
OrderedDict
3、默认字典(defaultdict)函数说明
defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型;
class defaultdict(dict):
"""
defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.
"""
'''
当不存在键时,仅在__getitem__调用中,默认字典可以不带参数以生成新值;
默认字典与普通字典基本相同;
所有参数都都与dict字典相同(包括关键字参数),执行时均被传递给dict的构造函数;
'''
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D. """
pass
'''
浅拷贝;
例如:
>>> from collections import defaultdict
>>> dd1 = defaultdict(list)
>>> dd1['k1']
[]
>>> dd1
defaultdict(<class 'list'>, {'k1': []})
>>> dd2 = dd1.copy()
>>> dd2
defaultdict(<class 'list'>, {'k1': []})
'''
def __copy__(self, *args, **kwargs): # real signature unknown
""" D.copy() -> a shallow copy of D. """
'''
浅拷贝,等同于D.copy();
'''
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
"""
defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments. # (copied from class doc)
"""
pass
'''
构造方法;
'''
def __missing__(self, key): # real signature unknown; restored from __doc__
"""
__missing__(key) # Called by __getitem__ for missing key; pseudo-code:
if self.default_factory is None: raise KeyError((key,))
self[key] = value = self.default_factory()
return value
"""
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
'''
返回pickling状态的信息;
'''
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
'''
x.__repr__()等同于repr(x)
转化为解释器可读取的形式,即转换为字符串格式;
'''
default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
defaultdict
4、可命名元组(namedtuple)函数说明
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型;
################################################################################
### namedtuple
################################################################################
_class_template = """\
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class {typename}(tuple):
'{typename}({arg_list})'
__slots__ = ()
_fields = {field_names!r}
def __new__(_cls, {arg_list}):
'Create new instance of {typename}({arg_list})'
return _tuple.__new__(_cls, ({arg_list}))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new {typename} object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != {num_fields:d}:
raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new {typename} object replacing specified fields with new values'
result = _self._make(map(kwds.pop, {field_names!r}, _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '({repr_fmt})' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return OrderedDict(zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
{field_defs}
"""
_repr_template = '{name}=%r'
_field_template = '''\
{name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
'''
def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
'''
返回具有命名字段的元组的新子类;
'''
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = str(typename)
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = '_%d' % index
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
'identifiers: %r' % name)
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
'keyword: %r' % name)
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
'%r' % name)
if name in seen:
raise ValueError('Encountered duplicate field name: %r' % name)
seen.add(name)
# Fill-in the class template
class_definition = _class_template.format(
typename = typename,
field_names = tuple(field_names),
num_fields = len(field_names),
arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
repr_fmt = ', '.join(_repr_template.format(name=name)
for name in field_names),
field_defs = '\n'.join(_field_template.format(index=index, name=name)
for index, name in enumerate(field_names))
)
# Execute the template string in a temporary namespace and support
# tracing utilities by setting a value for frame.f_globals['__name__']
namespace = dict(__name__='namedtuple_%s' % typename)
exec(class_definition, namespace)
result = namespace[typename]
result._source = class_definition
if verbose:
print(result._source)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
namedtuple
5、双向队列(deque)函数说明
一个线程安全的双向队列,可进可出,可以从两端添加和删除元素;
class deque(object):
"""
deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints. 提供了两端都可以操作的序列,这意味着,可以在序列前后都执行添加或删除;
"""
def append(self, *args, **kwargs): # real signature unknown
""" Add an element to the right side of the deque. """
pass
'''
在deque的右边添加一个元素;
例如:
>>> from collections import deque
>>> d = deque()
>>> d
deque([])
>>> d.append('a')
>>> d
deque(['a'])
>>> d.append('b')
>>> d
deque(['a', 'b'])
>>> d.append(['b','c'])
>>> d
deque(['a', 'a', ['b', 'c']])
>>> d.append('b','c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)
'''
def appendleft(self, *args, **kwargs): # real signature unknown
""" Add an element to the left side of the deque. """
pass
'''
在deque的左边添加一个元素;
例如:
>>> d = deque('a')
>>> d
deque(['a'])
>>> d.appendleft('b')
>>> d
deque(['b', 'a'])
'''
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from the deque. """
pass
'''
从deque中删除所有元素;
例如:
>>> d = deque(['a','b'])
>>> d
deque(['a', 'b'])
>>> d.clear()
>>> d
deque([])
'''
def count(self, value): # real signature unknown; restored from __doc__
""" D.count(value) -> integer -- return number of occurrences of value """
return 0
'''
返回值的出现次数;
例如:
>>> d = deque(['a','a'])
>>> d.count('a')
2
'''
def extend(self, *args, **kwargs): # real signature unknown
""" Extend the right side of the deque with elements from the iterable """
pass
'''
使用可迭代的元素扩展deque的右侧,即一次性可添加多个元素;
例如:
>>> d = deque(['a','b'])
>>> d
deque(['a', 'b'])
>>> d.extend(['c','d','e'])
>>> d
deque(['a', 'b', 'c', 'd', 'e'])
'''
def extendleft(self, *args, **kwargs): # real signature unknown
""" Extend the left side of the deque with elements from the iterable """
pass
'''
使用可迭代的元素扩展deque的左侧,即一次性可添加多个元素;
例如:
>>> d = deque(['a','b'])
>>> d
deque(['a', 'b'])
>>> d.extendleft(['c','d','e'])
>>> d
deque(['e', 'd', 'c', 'a', 'b'])
'''
def pop(self, *args, **kwargs): # real signature unknown
""" Remove and return the rightmost element. """
pass
'''
删除并返回最右侧的元素;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.pop()
'e'
'''
def popleft(self, *args, **kwargs): # real signature unknown
""" Remove and return the leftmost element. """
pass
'''
删除并返回最左侧的元素;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.popleft()
'a'
'''
def remove(self, value): # real signature unknown; restored from __doc__
""" D.remove(value) -- remove first occurrence of value. """
pass
'''
删除指定的一个值;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.remove()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)
>>> d.remove('a')
>>> d
deque(['b', 'c', 'd', 'e'])
>>> d.remove('c')
>>> d
deque(['b', 'd', 'e'])
>>> d.remove('b','d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (2 given)
'''
def reverse(self): # real signature unknown; restored from __doc__
""" D.reverse() -- reverse *IN PLACE* """
pass
'''
将元素反转;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.reverse()
>>> d
deque(['e', 'd', 'c', 'b', 'a'])
'''
def rotate(self, *args, **kwargs): # real signature unknown
""" Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """
pass
'''
将最后的n个元素向右反转(默认n = 1),如果n为负,则将最前的n个元素向左反转;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.rotate()
>>> d
deque(['e', 'a', 'b', 'c', 'd'])
>>> d.rotate(2)
>>> d
deque(['c', 'd', 'e', 'a', 'b'])
>>> d.rotate(-4)
>>> d
deque(['b', 'c', 'd', 'e', 'a'])
'''
def __copy__(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a deque. """
pass
'''
浅拷贝;
'''
def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass
'''
删除元素,等同于del;
例如:
>>> d = deque(['a','b','c','d','e'])
>>> d.__delitem__(1)
>>> d
deque(['a', 'c', 'd', 'e'])
>>> del d[2]
>>> d
deque(['a', 'c', 'e'])
'''
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
'''
等同于判断,返回布尔值;
例如:
>>> x = deque(['a','b','c','d','e'])
>>> y = deque(['a','b','c','d'])
>>> x.__eq__(y)
False
>>> x == y
False
>>> y = deque(['a','b','c','d','e'])
>>> x == y
True
'''
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
'''
返回队列指定下标的值,下标值需指定并为整数型,否则报错;
例如:
>>> x = deque(['a','b','c','d','e'])
>>> x.__getitem__(2)
'c'
>>> x[3]
'd'
'''
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
'''
大于等于判断,返回布尔值;
例如:
>>> x = deque(['a','b','c','d','e'])
>>> y = deque(['a','b','c','d'])
>>> x.__ge__(y)
True
>>> x >= y
True
'''
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
'''
大于判断,返回布尔值;
'''
def __iadd__(self, y): # real signature unknown; restored from __doc__
""" x.__iadd__(y) <==> x+=y """
pass
'''
自加,相当于+=;
'''
def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
"""
deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints.
# (copied from class doc)
"""
pass
'''
构造方法,执行x = deque()时自动调用deque函数;
'''
def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass
'''
在deque上返回一个迭代器;
'''
def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass
'''
返回队列长度;
例如:
>>> x = deque(['a','b','c','d','e'])
>>> x.__len__()
5
>>> len(x)
5
'''
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
'''
小于等于判断,返回布尔值;
'''
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
'''
小于判断,返回布尔值;
'''
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
'''
不等于判断,返回布尔值;
'''
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
'''
返回pickling的状态信息;
'''
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
'''
转化为解释器可读取的形式,即转换为字符串格式;
'''
def __reversed__(self): # real signature unknown; restored from __doc__
""" D.__reversed__() -- return a reverse iterator over the deque """
pass
'''
在deque上返回一个反向迭代器;
'''
def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass
'''
对队列里,指定的下标值进行修改,i需为整数,并且不能超过队列的下标范围;
例如:
>>> x = deque(['a','b','c','d','e'])
>>> x.__setitem__(2,'f')
>>> x
deque(['a', 'b', 'f', 'd', 'e'])
>>> x[4] = 'g'
>>> x
deque(['a', 'b', 'f', 'd', 'g'])
>>> x[5] = 'h'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: deque index out of range
'''
def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -- size of D in memory, in bytes """
pass
'''
获取内存中队列的大小,以字节为单位;
'''
maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""maximum size of a deque or None if unbounded"""
__hash__ = None
deque
6、单向队列(Queue)函数说明
Queue是python标准库中的线程安全的队列FIFO(先进先出)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递;
Python2中使用Queue的方法是,from Queue import Queue;
而Python3中使用Queue的方法是,from queue import Queue;
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
'''
Queue提供了一个基本的FIFO容器,使用方法很简单,maxsize是个整数,指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻塞,直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。
'''
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
'''
构造函数,执行x = queue()时自动调用Queue函数;
'''
def task_done(self):
'''Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
'''
意味着之前入队的一个任务已经完成;
由队列的消费者线程调用。每一个get()调用得到一个任务,接下来的task_done()调用告诉队列该任务已经处理完毕。
如果当前一个join()正在阻塞,它将在队列中的所有任务都处理完时恢复执行(即每一个由put()调用入队的任务都有一个对应的task_done()调用)。
如果调用的次数比在队列中放置的项目多,则引发ValueError;
'''
def join(self):
'''Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
'''
阻塞调用线程,直到队列中的所有任务被处理掉;
只要有数据被加入队列,未完成的任务数就会增加;
当消费者线程调用task_done()(意味着有消费者取得任务并完成任务),未完成的任务数就会减少;
当未完成的任务数降到0,join()解除阻塞;
'''
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize()
'''
返回队列的大致大小(不可靠!)
'''
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize()
'''
如果队列为空,返回True,否则返回False(不可靠!);
这种方法很可能在某个时候被删除。并由qsize() == 0来替代,但是要注意,不管是使用empty()还是qsize(),都有可能会在队列产生风险;
要创建需要等待所有排队任务完成的代码,首选的技术是使用join()方法;
'''
def full(self):
'''Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize()
'''
如果队列已满,返回True,否则返回False(不可靠!);
这种方法很可能在某个时候被删除。并由qsize() >= n来替代,但是要注意,不管是使用full()还是qsize(),都有可能会在队列产生风险;
'''
def put(self, item, block=True, timeout=None):
'''Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
'''
将项目放入队列;
如果可选的参数block为true,并且参数timeout为None(默认值)时,则表示队列需直到空闲时才可用;
如果参数timeout为一个非负数,则表示它最多阻塞“超时”多少秒,并且如果在那个时间内队列没有空余槽,则引发Full异常;
而当参数block为false时,则队列有空余槽时,就立即向项目放入队列中,否则引发Full异常(这种情况下,参数timeout不起作用)
'''
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
'''
从队列中删除并返回项目;
如果可选的参数block为true,并且参数timeout为None(默认值)时,则表示队列需直到有项目时才可用;
如果参数timeout为一个非负数,则表示它最多阻塞“超时”多少秒,并且如果在那个时间内没有可用的项目,则引发Empty异常;
而当参数block为false时,则项目可用就立即返回结果,否则引发Empty异常(这种情况下,参数timeout不起作用)
'''
def put_nowait(self, item):
'''Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False)
'''
没有阻塞时将项目放入队列;
只有当队列有空余槽时,才将项目入列;
否则引发Full异常;
'''
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
'''
没有阻塞时,从队列中删除并返回项目;
只有当队列有可用项目时,才获取项目;
否则引发Empty异常;
'''
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
'''
初始化队列;
'''
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
'''
将新项目放入队列;
'''
# Get an item from the queue
def _get(self):
return self.queue.popleft()
'''
从队列中获取项目
'''
Queue
Python基本数据类型(一)的更多相关文章
- python 基本数据类型分析
在python中,一切都是对象!对象由类创建而来,对象所拥有的功能都来自于类.在本节中,我们了解一下python基本数据类型对象具有哪些功能,我们平常是怎么使用的. 对于python,一切事物都是对象 ...
- python常用数据类型内置方法介绍
熟练掌握python常用数据类型内置方法是每个初学者必须具备的内功. 下面介绍了python常用的集中数据类型及其方法,点开源代码,其中对主要方法都进行了中文注释. 一.整型 a = 100 a.xx ...
- 闲聊之Python的数据类型 - 零基础入门学习Python005
闲聊之Python的数据类型 让编程改变世界 Change the world by program Python的数据类型 闲聊之Python的数据类型所谓闲聊,goosip,就是屁大点事可以咱聊上 ...
- python自学笔记(二)python基本数据类型之字符串处理
一.数据类型的组成分3部分:身份.类型.值 身份:id方法来看它的唯一标识符,内存地址靠这个查看 类型:type方法查看 值:数据项 二.常用基本数据类型 int 整型 boolean 布尔型 str ...
- Python入门-数据类型
一.变量 1)变量定义 name = 100(name是变量名 = 号是赋值号100是变量的值) 2)变量赋值 直接赋值 a=1 链式赋值 a=b=c=1 序列解包赋值 a,b,c = 1,2,3 ...
- Python基础:八、python基本数据类型
一.什么是数据类型? 我们人类可以很容易的分清数字与字符的区别,但是计算机并不能,计算机虽然很强大,但从某种角度上来看又很傻,除非你明确告诉它,"1"是数字,"壹&quo ...
- python之数据类型详解
python之数据类型详解 二.列表list (可以存储多个值)(列表内数字不需要加引号) sort s1=[','!'] # s1.sort() # print(s1) -->['!', ' ...
- Python特色数据类型(列表)(上)
Python从零开始系列连载(9)——Python特色数据类型(列表)(上) 原创 2017-10-07 王大伟 Python爱好者社区 列表 列表,可以是这样的: 分享了一波我的网易云音乐列表 今天 ...
- 【Python】-NO.97.Note.2.Python -【Python 基本数据类型】
1.0.0 Summary Tittle:[Python]-NO.97.Note.2.Python -[Python 基本数据类型] Style:Python Series:Python Since: ...
- python基本数据类型之集合
python基本数据类型之集合 集合是一种容器,用来存放不同元素. 集合有3大特点: 集合的元素必须是不可变类型(字符串.数字.元组): 集合中的元素不能重复: 集合是无序的. 在集合中直接存入lis ...
随机推荐
- 了解Linux系统
++++++++++++++++++++++++++++++++++++++++++++++++++++ 有用的参考链接: 带你初识Linux操作系统:https://www.linuxidc.com ...
- Kibana6.x.x——导航权限控制入门
按如下图所示设置: 用该用户登录后,界面如图所示: 但遗憾的是,根据官方论坛的说法,其它的导航隐藏控制,暂时还不支持. 参考:https://discuss.elastic.co/t/hide-ina ...
- jQuery中animate()方法以及$('body').animate({"scrollTop":top})不被Firefox支持问题的解决
$("body").animate({"scrollTop":top}): 只被chrome支持,而不被Firefox支持 $("html" ...
- Python 基础学习之字典
1.基础代码 ##第六章 字典学习 test={'} print(test['a']) print(test['b']) 返回结果为: black123 2.基础知识: Python中的字典是一系列键 ...
- python3 读取表格的数据
python3 读取表格的数据 xlrd1.1.0的下载网址:https://pypi.python.org/pypi/xlrd. xlrd1.1.0兼容python2和python3. python ...
- my09_mysql指定时间点恢复之binlog start-position
场景描述 ********************************************* 在远程服务器做的全备并已经恢复,同时使用binlog server备份binlog 之后,删除了库 ...
- mpdf Could not find image file (http://local.com/xxxxx)
记录一下昨天和今天遇到的,yii2使用mpdf的时候,图片是使用php方法生成的二维码,所以图片地址为http://local.com/xxxxx,url中携带不同的参数. 但是开启了 $mpdf-& ...
- flume failed to start agent because dependencies were not found in classpath
FLUME_CLASSPATH=/root/flume/lib/ copied comon jar files from hadoop folder to the flume folder. cp / ...
- npm常用技巧
npm中内置了大量的实用技巧,如何高效的使用它们是一件充满挑战的事情.学会下面11个技巧,将会让你在任何项目中使用npm都会事半功倍. 1.如何打开package的主页 npm home $packa ...
- SQL Server Reporting Service(SSRS) 第四篇 SSRS 常见问题总结
1. 如何让表头在每页显示(译) A. 打开高级模式: 在分组栏中点击Column Goups右侧的箭头选择高级模式; B. 找到第一个Static组 在Row Groups区域中(注意不是Colu ...