IT虾米网

Python基础之第二篇

luoye 2018年06月29日 编程语言 854 0

一、作用域

对作用域来说,只要变量在内存里面存在就可以使用:

1 if 1==1: 
2     name = 'saneri' 
3 print  name

二、三元运算

result =  值1  if  条件  else  值2

如果条件为真:result = 值1
如果条件为假:result = 值2

三、进制

  • 二进制,01
  • 八进制,01234567
  • 十进制,0123456789
  • 十六进制,0123456789ABCDE

 对于Python 一切事物都是对象,对象基于类创建.类里面保存了对象的方法和功能:

 通过type可以查看对象的类型
 dir(类型名)查看类中提供的所有功能
 help(类型名) 查看类中所有详细的功能
 help(类型名.功能名) 查看类中某功能的详细信息.

dir(list)  
私有方法'__add__', '__class__', '__contains__'     可能有多种执行方式 
 
非内置方法: 'append', 'count', 'extend', 'index', 'insert'  只有一种执行方式,通过对象.方法来调用.

一、整数

创建数字方法
i = 10
i = int(10)
i = int("10",base=2)

1 divmod(10,3)  求商和余数  ---》分页 
2 all()         接收一个序列,判断,所有值都是真,返回真,负责返回假. 
3 any()         只要有一个是真,就是真.
class int(object): 
    """ 
    int(x=0) -> int or long 
    int(x, base=10) -> int or long 
     
    Convert a number or string to an integer, or return 0 if no arguments 
    are given.  If x is floating point, the conversion truncates towards zero. 
    If x is outside the integer range, the function returns a long instead. 
     
    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) 
    4 
    """ 
    def bit_length(self):  
        """ 返回表示该数字的时占用的最少位数 """ 
        """ 
        int.bit_length() -> int 
         
        Number of bits necessary to represent self in binary. 
        >>> bin(37) 
        '0b100101' 
        >>> (37).bit_length() 
        6 
        """ 
        return 0 
 
    def conjugate(self, *args, **kwargs): # real signature unknown 
        """ 返回该复数的共轭复数 """ 
        """ Returns self, the complex conjugate of any int. """ 
        pass 
 
    def __abs__(self): 
        """ 返回绝对值 """ 
        """ x.__abs__() <==> abs(x) """ 
        pass 
 
    def __add__(self, y): 
        """ x.__add__(y) <==> x+y """ 
        pass 
 
    def __and__(self, y): 
        """ x.__and__(y) <==> x&y """ 
        pass 
 
    def __cmp__(self, y):  
        """ 比较两个数大小 """ 
        """ x.__cmp__(y) <==> cmp(x,y) """ 
        pass 
 
    def __coerce__(self, y): 
        """ 强制生成一个元组 """  
        """ x.__coerce__(y) <==> coerce(x, y) """ 
        pass 
 
    def __divmod__(self, y):  
        """ 相除,得到商和余数组成的元组 """  
        """ x.__divmod__(y) <==> divmod(x, y) """ 
        pass 
 
    def __div__(self, y):  
        """ x.__div__(y) <==> x/y """ 
        pass 
 
    def __float__(self):  
        """ 转换为浮点类型 """  
        """ x.__float__() <==> float(x) """ 
        pass 
 
    def __floordiv__(self, y):  
        """ x.__floordiv__(y) <==> x//y """ 
        pass 
 
    def __format__(self, *args, **kwargs): # real signature unknown 
        pass 
 
    def __getattribute__(self, name):  
        """ x.__getattribute__('name') <==> x.name """ 
        pass 
 
    def __getnewargs__(self, *args, **kwargs): # real signature unknown 
        """ 内部调用 __new__方法或创建对象时传入参数使用 """  
        pass 
 
    def __hash__(self):  
        """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" 
        """ x.__hash__() <==> hash(x) """ 
        pass 
 
    def __hex__(self):  
        """ 返回当前数的 十六进制 表示 """  
        """ x.__hex__() <==> hex(x) """ 
        pass 
 
    def __index__(self):  
        """ 用于切片,数字无意义 """ 
        """ 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) 时,自动调用,暂时忽略 """  
        """ 
        int(x=0) -> int or long 
        int(x, base=10) -> int or long 
         
        Convert a number or string to an integer, or return 0 if no arguments 
        are given.  If x is floating point, the conversion truncates towards zero. 
        If x is outside the integer range, the function returns a long instead. 
         
        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) 
        4 
        # (copied from class doc) 
        """ 
        pass 
 
    def __int__(self):  
        """ 转换为整数 """  
        """ x.__int__() <==> int(x) """ 
        pass 
 
    def __invert__(self):  
        """ x.__invert__() <==> ~x """ 
        pass 
 
    def __long__(self):  
        """ 转换为长整数 """  
        """ x.__long__() <==> long(x) """ 
        pass 
 
    def __lshift__(self, y):  
        """ x.__lshift__(y) <==> x<<y """ 
        pass 
 
    def __mod__(self, y):  
        """ x.__mod__(y) <==> x%y """ 
        pass 
 
    def __mul__(self, y):  
        """ x.__mul__(y) <==> x*y """ 
        pass 
 
    def __neg__(self):  
        """ x.__neg__() <==> -x """ 
        pass 
 
    @staticmethod # known case of __new__ 
    def __new__(S, *more):  
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 
        pass 
 
    def __nonzero__(self):  
        """ x.__nonzero__() <==> x != 0 """ 
        pass 
 
    def __oct__(self):  
        """ 返回改值的 八进制 表示 """  
        """ x.__oct__() <==> oct(x) """ 
        pass 
 
    def __or__(self, y):  
        """ x.__or__(y) <==> x|y """ 
        pass 
 
    def __pos__(self):  
        """ x.__pos__() <==> +x """ 
        pass 
 
    def __pow__(self, y, z=None):  
        """ 幂,次方 """  
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 
        pass 
 
    def __radd__(self, y):  
        """ x.__radd__(y) <==> y+x """ 
        pass 
 
    def __rand__(self, y):  
        """ x.__rand__(y) <==> y&x """ 
        pass 
 
    def __rdivmod__(self, y):  
        """ x.__rdivmod__(y) <==> divmod(y, x) """ 
        pass 
 
    def __rdiv__(self, y):  
        """ x.__rdiv__(y) <==> y/x """ 
        pass 
 
    def __repr__(self):  
        """转化为解释器可读取的形式 """ 
        """ x.__repr__() <==> repr(x) """ 
        pass 
 
    def __str__(self):  
        """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" 
        """ x.__str__() <==> str(x) """ 
        pass 
 
    def __rfloordiv__(self, y):  
        """ x.__rfloordiv__(y) <==> y//x """ 
        pass 
 
    def __rlshift__(self, y):  
        """ x.__rlshift__(y) <==> y<<x """ 
        pass 
 
    def __rmod__(self, y):  
        """ x.__rmod__(y) <==> y%x """ 
        pass 
 
    def __rmul__(self, y):  
        """ x.__rmul__(y) <==> y*x """ 
        pass 
 
    def __ror__(self, y):  
        """ x.__ror__(y) <==> y|x """ 
        pass 
 
    def __rpow__(self, x, z=None):  
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 
        pass 
 
    def __rrshift__(self, y):  
        """ x.__rrshift__(y) <==> y>>x """ 
        pass 
 
    def __rshift__(self, y):  
        """ x.__rshift__(y) <==> x>>y """ 
        pass 
 
    def __rsub__(self, y):  
        """ x.__rsub__(y) <==> y-x """ 
        pass 
 
    def __rtruediv__(self, y):  
        """ x.__rtruediv__(y) <==> y/x """ 
        pass 
 
    def __rxor__(self, y):  
        """ x.__rxor__(y) <==> y^x """ 
        pass 
 
    def __sub__(self, y):  
        """ x.__sub__(y) <==> x-y """ 
        pass 
 
    def __truediv__(self, y):  
        """ x.__truediv__(y) <==> x/y """ 
        pass 
 
    def __trunc__(self, *args, **kwargs):  
        """ 返回数值被截取为整形的值,在整形中无意义 """ 
        pass 
 
    def __xor__(self, y):  
        """ x.__xor__(y) <==> x^y """ 
        pass 
 
    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default 
    """ 分母 = 1 """ 
    """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"""
int

二、长整型

可能如:2147483649、9223372036854775807

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

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

三、浮点型

如:3.14、2.88

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

class float(object): 
    """ 
    float(x) -> floating point number 
     
    Convert a string or number to a floating point number, if possible. 
    """ 
    def as_integer_ratio(self):    
        """ 获取改值的最简比 """ 
        """ 
        float.as_integer_ratio() -> (int, int) 
 
        Return a pair of integers, whose ratio is exactly equal to the original 
        float and with a positive denominator. 
        Raise OverflowError on infinities and a ValueError on NaNs. 
 
        >>> (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 
        """ Return self, the complex conjugate of any float. """ 
        pass 
 
    def fromhex(self, string):    
        """ 将十六进制字符串转换成浮点型 """ 
        """ 
        float.fromhex(string) -> float 
         
        Create a floating-point number from a hexadecimal string. 
        >>> float.fromhex('0x1.ffffp10') 
        2047.984375 
        >>> float.fromhex('-0x1p-1074') 
        -4.9406564584124654e-324 
        """ 
        return 0.0 
 
    def hex(self):    
        """ 返回当前值的 16 进制表示 """ 
        """ 
        float.hex() -> string 
         
        Return a hexadecimal representation of a floating-point number. 
        >>> (-0.1).hex() 
        '-0x1.999999999999ap-4' 
        >>> 3.14159.hex() 
        '0x1.921f9f01b866ep+1' 
        """ 
        return "" 
 
    def is_integer(self, *args, **kwargs): # real signature unknown 
        """ Return True if the float is an integer. """ 
        pass 
 
    def __abs__(self):    
        """ x.__abs__() <==> abs(x) """ 
        pass 
 
    def __add__(self, y):    
        """ x.__add__(y) <==> x+y """ 
        pass 
 
    def __coerce__(self, y):    
        """ x.__coerce__(y) <==> coerce(x, y) """ 
        pass 
 
    def __divmod__(self, y):    
        """ x.__divmod__(y) <==> divmod(x, y) """ 
        pass 
 
    def __div__(self, y):    
        """ x.__div__(y) <==> x/y """ 
        pass 
 
    def __eq__(self, y):    
        """ x.__eq__(y) <==> x==y """ 
        pass 
 
    def __float__(self):    
        """ x.__float__() <==> float(x) """ 
        pass 
 
    def __floordiv__(self, y):    
        """ x.__floordiv__(y) <==> x//y """ 
        pass 
 
    def __format__(self, format_spec):    
        """ 
        float.__format__(format_spec) -> string 
         
        Formats the float according to format_spec. 
        """ 
        return "" 
 
    def __getattribute__(self, name):    
        """ x.__getattribute__('name') <==> x.name """ 
        pass 
 
    def __getformat__(self, typestr):    
        """ 
        float.__getformat__(typestr) -> string 
         
        You probably don't want to use this function.  It exists mainly to be 
        used in Python's test suite. 
         
        typestr must be 'double' or '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 
        pass 
 
    def __ge__(self, y):    
        """ x.__ge__(y) <==> x>=y """ 
        pass 
 
    def __gt__(self, y):    
        """ x.__gt__(y) <==> x>y """ 
        pass 
 
    def __hash__(self):    
        """ x.__hash__() <==> hash(x) """ 
        pass 
 
    def __init__(self, x):    
        pass 
 
    def __int__(self):    
        """ x.__int__() <==> int(x) """ 
        pass 
 
    def __le__(self, y):    
        """ x.__le__(y) <==> x<=y """ 
        pass 
 
    def __long__(self):    
        """ x.__long__() <==> long(x) """ 
        pass 
 
    def __lt__(self, y):    
        """ x.__lt__(y) <==> x<y """ 
        pass 
 
    def __mod__(self, y):    
        """ x.__mod__(y) <==> x%y """ 
        pass 
 
    def __mul__(self, y):    
        """ x.__mul__(y) <==> x*y """ 
        pass 
 
    def __neg__(self):    
        """ x.__neg__() <==> -x """ 
        pass 
 
    @staticmethod # known case of __new__ 
    def __new__(S, *more):    
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 
        pass 
 
    def __ne__(self, y):    
        """ x.__ne__(y) <==> x!=y """ 
        pass 
 
    def __nonzero__(self):    
        """ x.__nonzero__() <==> x != 0 """ 
        pass 
 
    def __pos__(self):    
        """ x.__pos__() <==> +x """ 
        pass 
 
    def __pow__(self, y, z=None):    
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 
        pass 
 
    def __radd__(self, y):    
        """ x.__radd__(y) <==> y+x """ 
        pass 
 
    def __rdivmod__(self, y):    
        """ x.__rdivmod__(y) <==> divmod(y, x) """ 
        pass 
 
    def __rdiv__(self, y):    
        """ x.__rdiv__(y) <==> y/x """ 
        pass 
 
    def __repr__(self):    
        """ x.__repr__() <==> repr(x) """ 
        pass 
 
    def __rfloordiv__(self, y):    
        """ x.__rfloordiv__(y) <==> y//x """ 
        pass 
 
    def __rmod__(self, y):    
        """ x.__rmod__(y) <==> y%x """ 
        pass 
 
    def __rmul__(self, y):    
        """ x.__rmul__(y) <==> y*x """ 
        pass 
 
    def __rpow__(self, x, z=None):    
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 
        pass 
 
    def __rsub__(self, y):    
        """ x.__rsub__(y) <==> y-x """ 
        pass 
 
    def __rtruediv__(self, y):    
        """ x.__rtruediv__(y) <==> y/x """ 
        pass 
 
    def __setformat__(self, typestr, fmt):    
        """ 
        float.__setformat__(typestr, fmt) -> None 
         
        You probably don't want to use this function.  It exists mainly to be 
        used in Python's test suite. 
         
        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):    
        """ x.__str__() <==> str(x) """ 
        pass 
 
    def __sub__(self, y):    
        """ x.__sub__(y) <==> x-y """ 
        pass 
 
    def __truediv__(self, y):    
        """ x.__truediv__(y) <==> x/y """ 
        pass 
 
    def __trunc__(self, *args, **kwargs): # real signature unknown 
        """ Return the Integral closest to x between 0 and x. """ 
        pass 
 
    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default 
    """the imaginary part of a complex number""" 
 
    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default 
    """the real part of a complex number"""
float
_hash__   在字典查找中,哈希值用于快速比较字典的键 
__hex__   """ 返回当前数的 十六进制 表示 """                   
__oct__   返回改值的 八进制 表示 """

四、字符串

如:'saneri'、'abcd'

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

  1 """ 
  2     str(object='') -> string 
  3      
  4     Return a nice string representation of the object. 
  5     If the argument is a string, the return value is the same object. 
  6     """ 
  7     def capitalize(self):   
  8         """ 首字母变大写 """ 
  9         """ 
 10         S.capitalize() -> string 
 11          
 12         Return a copy of the string S with only its first character 
 13         capitalized. 
 14         """ 
 15         return "" 
 16       
 17     def center(self, width, fillchar=None):   
 18         """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ 
 19         """ 
 20         S.center(width[, fillchar]) -> string 
 21        >>> s = "alex"  
 22         >>> s.center(30, "*")     
 23            '*************alex*************' 
 24         Return S centered in a string of length width. Padding is 
 25         done using the specified fill character (default is a space) 
 26         """ 
 27         return "" 
 28  
 29     def count(self, sub, start=None, end=None):   
 30         """ 子序列个数 """ 
 31         """ 
 32         S.count(sub[, start[, end]]) -> int 
 33         s.count("a",0,5)  start,end找,下标的位置 
 34         Return the number of non-overlapping occurrences of substring sub in 
 35         string S[start:end].  Optional arguments start and end are interpreted 
 36         as in slice notation. 
 37         """ 
 38         return 0 
 39  
 40     def decode(self, encoding=None, errors=None):   
 41         """ 解码""" 
 42         """ 
 43         S.decode([encoding[,errors]]) -> object 
 44          
 45         Decodes S using the codec registered for encoding. encoding defaults 
 46         to the default encoding. errors may be given to set a different error 
 47         handling scheme. Default is 'strict' meaning that encoding errors raise 
 48         a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' 
 49         as well as any other name registered with codecs.register_error that is 
 50         able to handle UnicodeDecodeErrors. 
 51         """ 
 52         return object() 
 53  
 54     def encode(self, encoding=None, errors=None):   
 55         """ 编码,针对unicode """ 
 56         """ 
 57         S.encode([encoding[,errors]]) -> object 
 58          
 59         Encodes S using the codec registered for encoding. encoding defaults 
 60         to the default encoding. errors may be given to set a different error 
 61         handling scheme. Default is 'strict' meaning that encoding errors raise 
 62         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 
 63         'xmlcharrefreplace' as well as any other name registered with 
 64         codecs.register_error that is able to handle UnicodeEncodeErrors. 
 65         """ 
 66         return object() 
 67  
 68     def endswith(self, suffix, start=None, end=None):   
 69         """ 是否以 xxx 结束 """ 
 70         """ 
 71         S.endswith(suffix[, start[, end]]) -> bool 
 72          
 73         Return True if S ends with the specified suffix, False otherwise. 
 74         With optional start, test S beginning at that position. 
 75         With optional end, stop comparing S at that position. 
 76         suffix can also be a tuple of strings to try. 
 77         """ 
 78         return False 
 79  
 80     def expandtabs(self, tabsize=None):   
 81         """ 将tab转换成空格,默认一个tab转换成8个空格 """ 
 82         """ 
 83         S.expandtabs([tabsize]) -> string 
 84          
 85         Return a copy of S where all tab characters are expanded using spaces. 
 86         If tabsize is not given, a tab size of 8 characters is assumed. 
 87         """ 
 88         return "" 
 89  
 90     def find(self, sub, start=None, end=None):   
 91         """ 寻找子序列位置,如果没找到,则异常 """ 
 92         """ 
 93         S.find(sub [,start [,end]]) -> int 
 94          
 95         Return the lowest index in S where substring sub is found, 
 96         such that sub is contained within S[start:end].  Optional 
 97         arguments start and end are interpreted as in slice notation. 
 98          
 99         Return -1 on failure. 
100         """ 
101         return 0 
102  
103     def format(*args, **kwargs): # known special case of str.format 
104         """ 字符串格式化,动态参数,将函数式编程时细说 """ 
105         """ 
106         S.format(*args, **kwargs) -> string 
107          
108         Return a formatted version of S, using substitutions from args and kwargs. 
109         The substitutions are identified by braces ('{' and '}'). 
110         """ 
111         pass 
112  
113     def index(self, sub, start=None, end=None):   
114         """ 子序列位置,如果没找到,则返回-1  """ 
115         S.index(sub [,start [,end]]) -> int 
116          
117         Like S.find() but raise ValueError when the substring is not found. 
118         """ 
119         return 0 
120  
121     def isalnum(self):   
122         """ 是否是字母和数字 """ 
123         """ 
124         S.isalnum() -> bool 
125          
126         Return True if all characters in S are alphanumeric 
127         and there is at least one character in S, False otherwise. 
128         """ 
129         return False 
130  
131     def isalpha(self):   
132         """ 是否是字母 """ 
133         """ 
134         S.isalpha() -> bool 
135          
136         Return True if all characters in S are alphabetic 
137         and there is at least one character in S, False otherwise. 
138         """ 
139         return False 
140  
141     def isdigit(self):   
142         """ 是否是数字 """ 
143         """ 
144         S.isdigit() -> bool 
145          
146         Return True if all characters in S are digits 
147         and there is at least one character in S, False otherwise. 
148         """ 
149         return False 
150  
151     def islower(self):   
152         """ 是否小写 """ 
153         """ 
154         S.islower() -> bool 
155          
156         Return True if all cased characters in S are lowercase and there is 
157         at least one cased character in S, False otherwise. 
158         """ 
159         return False 
160  
161     def isspace(self):   
162         """ 
163         S.isspace() -> bool 
164          
165         Return True if all characters in S are whitespace 
166         and there is at least one character in S, False otherwise. 
167         """ 
168         return False 
169  
170     def istitle(self):   
171         """ 
172         S.istitle() -> bool 
173          
174         Return True if S is a titlecased string and there is at least one 
175         character in S, i.e. uppercase characters may only follow uncased 
176         characters and lowercase characters only cased ones. Return False 
177         otherwise. 
178         """ 
179         return False 
180  
181     def isupper(self):   
182         """ 
183         S.isupper() -> bool 
184          
185         Return True if all cased characters in S are uppercase and there is 
186         at least one cased character in S, False otherwise. 
187         """ 
188         return False 
189  
190     def join(self, iterable):   
191         """ 连接 """ 
192         """ 
193         S.join(iterable) -> string 
194          
195         Return a string which is the concatenation of the strings in the 
196         iterable.  The separator between elements is S. 
197         """ 
198         return "" 
199  
200     def ljust(self, width, fillchar=None):   
201         """ 内容左对齐,右侧填充 """ 
202         """ 
203         S.ljust(width[, fillchar]) -> string 
204          
205         Return S left-justified in a string of length width. Padding is 
206         done using the specified fill character (default is a space). 
207         """ 
208         return "" 
209  
210     def lower(self):   
211         """ 变小写 """ 
212         """ 
213         S.lower() -> string 
214          
215         Return a copy of the string S converted to lowercase. 
216         """ 
217         return "" 
218  
219     def lstrip(self, chars=None):   
220         """ 移除左侧空白 """ 
221         """ 
222         S.lstrip([chars]) -> string or unicode 
223          
224         Return a copy of the string S with leading whitespace removed. 
225         If chars is given and not None, remove characters in chars instead. 
226         If chars is unicode, S will be converted to unicode before stripping 
227         """ 
228         return "" 
229  
230     def partition(self, sep):   
231         """ 分割,前,中,后三部分 """ 
232         """ 
233         S.partition(sep) -> (head, sep, tail) 
234          
235         Search for the separator sep in S, and return the part before it, 
236         the separator itself, and the part after it.  If the separator is not 
237         found, return S and two empty strings. 
238         """ 
239         pass 
240  
241     def replace(self, old, new, count=None):   
242         """ 替换 """ 
243         """ 
244         S.replace(old, new[, count]) -> string 
245          
246         Return a copy of string S with all occurrences of substring 
247         old replaced by new.  If the optional argument count is 
248         given, only the first count occurrences are replaced. 
249         """ 
250         return "" 
251  
252     def rfind(self, sub, start=None, end=None):   
253         """ 
254         S.rfind(sub [,start [,end]]) -> int 
255          
256         Return the highest index in S where substring sub is found, 
257         such that sub is contained within S[start:end].  Optional 
258         arguments start and end are interpreted as in slice notation. 
259          
260         Return -1 on failure. 
261         """ 
262         return 0 
263  
264     def rindex(self, sub, start=None, end=None):   
265         """ 
266         S.rindex(sub [,start [,end]]) -> int 
267          
268         Like S.rfind() but raise ValueError when the substring is not found. 
269         """ 
270         return 0 
271  
272     def rjust(self, width, fillchar=None):   
273         """ 
274         S.rjust(width[, fillchar]) -> string 
275          
276         Return S right-justified in a string of length width. Padding is 
277         done using the specified fill character (default is a space) 
278         """ 
279         return "" 
280  
281     def rpartition(self, sep):   
282         """ 
283         S.rpartition(sep) -> (head, sep, tail) 
284          
285         Search for the separator sep in S, starting at the end of S, and return 
286         the part before it, the separator itself, and the part after it.  If the 
287         separator is not found, return two empty strings and S. 
288         """ 
289         pass 
290  
291     def rsplit(self, sep=None, maxsplit=None):   
292         """ 
293         S.rsplit([sep [,maxsplit]]) -> list of strings 
294          
295         Return a list of the words in the string S, using sep as the 
296         delimiter string, starting at the end of the string and working 
297         to the front.  If maxsplit is given, at most maxsplit splits are 
298         done. If sep is not specified or is None, any whitespace string 
299         is a separator. 
300         """ 
301         return [] 
302  
303     def rstrip(self, chars=None):   
304         """ 
305         S.rstrip([chars]) -> string or unicode 
306          
307         Return a copy of the string S with trailing whitespace removed. 
308         If chars is given and not None, remove characters in chars instead. 
309         If chars is unicode, S will be converted to unicode before stripping 
310         """ 
311         return "" 
312  
313     def split(self, sep=None, maxsplit=None):   
314         """ 分割, maxsplit最多分割几次 """ 
315         """ 
316         S.split([sep [,maxsplit]]) -> list of strings 
317          
318         Return a list of the words in the string S, using sep as the 
319         delimiter string.  If maxsplit is given, at most maxsplit 
320         splits are done. If sep is not specified or is None, any 
321         whitespace string is a separator and empty strings are removed 
322         from the result. 
323         """ 
324         return [] 
325  
326     def splitlines(self, keepends=False):   
327         """ 根据换行分割 """ 
328         """ 
329         S.splitlines(keepends=False) -> list of strings 
330          
331         Return a list of the lines in S, breaking at line boundaries. 
332         Line breaks are not included in the resulting list unless keepends 
333         is given and true. 
334         """ 
335         return [] 
336  
337     def startswith(self, prefix, start=None, end=None):   
338         """ 是否起始 """ 
339         """ 
340         S.startswith(prefix[, start[, end]]) -> bool 
341          
342         Return True if S starts with the specified prefix, False otherwise. 
343         With optional start, test S beginning at that position. 
344         With optional end, stop comparing S at that position. 
345         prefix can also be a tuple of strings to try. 
346         """ 
347         return False 
348  
349     def strip(self, chars=None):   
350         """ 移除两端空白 """ 
351         """ 
352         S.strip([chars]) -> string or unicode 
353          
354         Return a copy of the string S with leading and trailing 
355         whitespace removed. 
356         If chars is given and not None, remove characters in chars instead. 
357         If chars is unicode, S will be converted to unicode before stripping 
358         """ 
359         return "" 
360  
361     def swapcase(self):   
362         """ 大写变小写,小写变大写 """ 
363         """ 
364         S.swapcase() -> string 
365          
366         Return a copy of the string S with uppercase characters 
367         converted to lowercase and vice versa. 
368         """ 
369         return "" 
370  
371     def title(self):   
372         """ 
373         S.title() -> string 
374          
375         Return a titlecased version of S, i.e. words start with uppercase 
376         characters, all remaining cased characters have lowercase. 
377         """ 
378         return "" 
379  
380     def translate(self, table, deletechars=None):   
381         """ 
382         转换,需要先做一个对应表,最后一个表示删除字符集合 
383         intab = "aeiou" 
384         outtab = "12345" 
385         trantab = maketrans(intab, outtab) 
386         str = "this is string example....wow!!!" 
387         print str.translate(trantab, 'xm') 
388         """ 
389  
390         """ 
391         S.translate(table [,deletechars]) -> string 
392          
393         Return a copy of the string S, where all characters occurring 
394         in the optional argument deletechars are removed, and the 
395         remaining characters have been mapped through the given 
396         translation table, which must be a string of length 256 or None. 
397         If the table argument is None, no translation is applied and 
398         the operation simply removes the characters in deletechars. 
399         """ 
400         return "" 
401  
402     def upper(self):   
403         """ 
404         S.upper() -> string 
405          
406         Return a copy of the string S converted to uppercase. 
407         """ 
408         return "" 
409  
410     def zfill(self, width):   
411         """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""" 
412         """ 
413         S.zfill(width) -> string 
414          
415         Pad a numeric string S with zeros on the left, to fill a field 
416         of the specified width.  The string S is never truncated. 
417         """ 
418         return "" 
419  
420     def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown 
421         pass 
422  
423     def _formatter_parser(self, *args, **kwargs): # real signature unknown 
424         pass 
425  
426     def __add__(self, y):   
427         """ x.__add__(y) <==> x+y """ 
428         pass 
429  
430     def __contains__(self, y):   
431         """ x.__contains__(y) <==> y in x """ 
432         pass 
433  
434     def __eq__(self, y):   
435         """ x.__eq__(y) <==> x==y """ 
436         pass 
437  
438     def __format__(self, format_spec):   
439         """ 
440         S.__format__(format_spec) -> string 
441          
442         Return a formatted version of S as described by format_spec. 
443         """ 
444         return "" 
445  
446     def __getattribute__(self, name):   
447         """ x.__getattribute__('name') <==> x.name """ 
448         pass 
449  
450     def __getitem__(self, y):   
451         """ x.__getitem__(y) <==> x[y] """ 
452         pass 
453  
454     def __getnewargs__(self, *args, **kwargs): # real signature unknown 
455         pass 
456  
457     def __getslice__(self, i, j):   
458         """ 
459         x.__getslice__(i, j) <==> x[i:j] 
460                     
461                    Use of negative indices is not supported. 
462         """ 
463         pass 
464  
465     def __ge__(self, y):   
466         """ x.__ge__(y) <==> x>=y """ 
467         pass 
468  
469     def __gt__(self, y):   
470         """ x.__gt__(y) <==> x>y """ 
471         pass 
472  
473     def __hash__(self):   
474         """ x.__hash__() <==> hash(x) """ 
475         pass 
476  
477     def __init__(self, string=''): # known special case of str.__init__ 
478         """ 
479         str(object='') -> string 
480          
481         Return a nice string representation of the object. 
482         If the argument is a string, the return value is the same object. 
483         # (copied from class doc) 
484         """ 
485         pass 
486  
487     def __len__(self):   
488         """ x.__len__() <==> len(x) """ 
489         pass 
490  
491     def __le__(self, y):   
492         """ x.__le__(y) <==> x<=y """ 
493         pass 
494  
495     def __lt__(self, y):   
496         """ x.__lt__(y) <==> x<y """ 
497         pass 
498  
499     def __mod__(self, y):   
500         """ x.__mod__(y) <==> x%y """ 
501         pass 
502  
503     def __mul__(self, n):   
504         """ x.__mul__(n) <==> x*n """ 
505         pass 
506  
507     @staticmethod # known case of __new__ 
508     def __new__(S, *more):   
509         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 
510         pass 
511  
512     def __ne__(self, y):   
513         """ x.__ne__(y) <==> x!=y """ 
514         pass 
515  
516     def __repr__(self):   
517         """ x.__repr__() <==> repr(x) """ 
518         pass 
519  
520     def __rmod__(self, y):   
521         """ x.__rmod__(y) <==> y%x """ 
522         pass 
523  
524     def __rmul__(self, n):   
525         """ x.__rmul__(n) <==> n*x """ 
526         pass 
527  
528     def __sizeof__(self):   
529         """ S.__sizeof__() -> size of S in memory, in bytes """ 
530         pass 
531  
532     def __str__(self):   
533         """ x.__str__() <==> str(x) """ 
534         pass 
535  
536 str
str

五、列表

List是处理和存放一组数据的列表

如:[11,22,33]、['saneri', 'alex']

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

List操作包含以下函数:
cmp(list1, list2):    比较两个列表的元素,两个元素相同返回0,前大后小返回1,前小后大返回-1
len(list):                列表元素个数
max(list):              返回列表元素最大值
min(list):               返回列表元素最小值
list('var'):               将元素转换为列表
del L[1]                   删除指定下标的元素
del L[1:3]                删除指定下标范围的元素

List操作包含以下方法:
L.append('var')        append方法用于在列表的尾部追加元素,参数'var'是插入元素的值
L.insert(index,'var')     用于将对象插入到列表中,俩个参数,第一个是索引位置,第二个插入的元素对象.
L.pop()            返回列表最后一个元素,并从List中删除.
Lpop(index)         返回列表索引的元素,并删除.
L.count(var)          该元素在列表中出现的个数
L.index('var')         取出元素的位置(下标),无则抛出异常.
L.remove('var')        remove方法用于从列表中移除第一次的值(值如果有重复则删除第一个)
L.sort()           排序
L.reverse()          倒序
L.extend(list1)        extend方法用于将两个列表合并,将list1列表的值添加到L列表的后面。

Python列表脚本操作符:

List 中 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

Python列表截取:
Python的列表截取与字符串操作类型,如下所示:

L = ['spam', 'Spam', 'SPAM!','xusandu']

实例:

 1 >>> ShoppingList = ['car','clothers','iphone']                  //定义列表 
 2 >>> ShoppingList.append('Alex')                        //在列表中插入'Alex'字符 
 3 >>> ShoppingList                                    //查看列表 
 4 ['car', 'clothers', 'iphone', 'Alex'] 
 5 >>> ShoppingList.insert(0,'top')                    //在列表下标为零处(即列表第一个元素),插入‘top’元素 
 6 >>> ShoppingList 
 7 ['top', 'car', 'clothers', 'iphone', 'Alex'] 
 8 >>>  
 9 >>> ShoppingList[0]                        //查看下标为零的元素 
10 'top' 
11 >>> ShoppingList[2]                        //查看下标为2的元素 
12 'clothers' 
13 >>> ShoppingList[0] = 'car'                  //将下标为0的元素(即‘top’字符)替换为‘car’   
14 >>> ShoppingList 
15 ['car', 'car', 'clothers', 'iphone', 'Alex'] 
16 >>> ShoppingList.pop()                    //列表最后一个元素(Alex),并从List中删除掉 
17 'Alex' 
18 >>> ShoppingList 
19 ['car', 'car', 'clothers', 'iphone'] 
20 >>>  
21 >>> ShoppingList.remove('iphone')             //从列表中移除'iphone'元素 
22 >>> ShoppingList 
23 ['car', 'car', 'clothers'] 
24 >>>  
25 >>> ShoppingList.append('rain') 
26 >>> ShoppingList.count('car')                //统计列表中元素'car'的个数 
27 2 
28 >>> 'car' in ShoppingList                  //List列表中查找'car'元素,如果存在则返回Ture 
29 True 
30 >>>  
31 >>> ShoppingList 
32 ['car', 'car', 'clothers', 'rain'] 
33 >>> ShoppingList.index('rain') 
34 3 
35 >>> ShoppingList 
36 ['car', 'car', 'clothers', 'rain'] 
37 >>> del ShoppingList[0]                //使用del 函数删除List中下标为0的元素. 
38 >>> ShoppingList        
39 ['car', 'clothers', 'rain'] 
40 >>> 

六、元组(tuple)

不可变序列-----元组 tuple 
元组通过圆括号中用逗号分隔的项目定义,不可以添加和删除元组.

如:(11,22,33)、('saneri', 'alex')

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

1 >>> name_tuple = ('a','b','c','a','b') 
2 >>> type(name_tuple) 
3 <type 'tuple'> 
4 >>> name_tuple.count('a') 
5 2 
6 >>> name_tuple.index('b')             //获取b元素下标位置. 
7 1

七、字典

字典是Python语言中唯一的映射类型。
映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表。
字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。

技巧:
字典中包含列表:dict = {"ZhangSan" : ['23','IT'],"Lisi" : ['22','dota']}
字典中包含字典:dict = {"Wangwu" : {"age" : 23,"job":"IT"},"Song" : {"age":22,"job":"dota"}}

Dict 操作包含以下方法:
D = {"ZhangSan" : ['23','IT'],"Lisi" : ['22','dota']}

D.clear()          清空字典D中的内容
D.keys()           查看字典所有主键

D.values()         查看字典所有value内容

D.popitem()        默认删除第一个键值

D.has_key('rain')     查询字典中是否有某个键

D['James'] = '23'     添加新item到字典

str(D)          输出字典可打印的字符串表示

del D['rain']      删除item

cmp(a,b)        首先比较主键长度,然后比较键大小,然后比较键值大小,(第一个大返回1,小返回-1,一样返回0)

D.fromkeys(seq[, value]))    fromkeys()方法从序列键和值设置为value来创建一个新的字典。实例如下:

 1 seq = ('name', 'age', 'sex') 
 2 dict = dict.fromkeys(seq) 
 3 print "New Dictionary : %s" %  str(dict) 
 4  
 5 dict = dict.fromkeys(seq, 10) 
 6 print "New Dictionary : %s" %  str(dict) 
 7  
 8 当我们运行上面的程序,它会产生以下结果: 
 9 New Dictionary : {'age': None, 'name': None, 'sex': None} 
10 New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
fromkeys方法

setdefault()          setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

 1 dict.setdefault(key, default=None) 
 2 key -- 查找的键值. 
 3   
 4 default -- 键不存在时,设置的默认键值。  
 5 dict = {'Name': 'Zara', 'Age': 7} 
 6  
 7 print "Value : %s" %  dict.setdefault('Age', None) 
 8 print "Value : %s" %  dict.setdefault('Sex', None) 
 9 以上实例输出结果为: 
10 Value : 7 
11 Value : None
setdefault

每个字典具备如下功能:

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

八、set集合

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

a &b 交集
a | b 并集
a ^ b 取出非交集的数
a -b a里面有b里面没有

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

九、collection系列:

1、计数器(counter)

Counter是对字典类型的补充,用于追踪值的出现次数。

具备字典的所有功能 + 自己的功能:

1 c = Counter('abcdeabcdabcaba') 
2 print c 
3 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

2、有序字典(orderedDict )

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

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

需求:

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。 
即: {'k1': 大于66 , 'k2': 小于66}defaultdict字典解决方法
 1 values = [11, 22, 33,44,55,66,77,88,99,90] 
 2  
 3 my_dict = {} 
 4  
 5 for value in  values: 
 6     if value>66: 
 7         if my_dict.has_key('k1'): 
 8             my_dict['k1'].append(value) 
 9         else: 
10             my_dict['k1'] = [value] 
11     else: 
12         if my_dict.has_key('k2'): 
13             my_dict['k2'].append(value) 
14         else: 
15             my_dict['k2'] = [value]
原生字典解决方法
 1 from collections import defaultdict 
 2  
 3 values = [11, 22, 33,44,55,66,77,88,99,90] 
 4  
 5 my_dict = defaultdict(list) 
 6  
 7 for value in  values: 
 8     if value>66: 
 9         my_dict['k1'].append(value) 
10     else: 
11         my_dict['k2'].append(value)
defaultdict字典解决方法

4、可命名元组(namedtuple)

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型.

1 import collections 
2 Mytuple = collections.namedtuple('Mytuple',['x','y','z']) 
3 new = Mytuple(1,2,3) 
4 print new 
5 Mytuple(x=1, y=2, z=3)

5、双向队列(deque)

 两边都可以存取,线程安全的)   在collection模块中

  单向队列:先进先出(FIFO)
  栈:弹夹(后进的先出) 再Queue模块中

1 >>> import Queue 
2         >>> Q = Queue.Queue(10)           最多插入10个数 
3         >>> Q.put(1)                          向队列中添加值 
4         >>> Q.put(2) 
5         >>> Q.put(3) 
6         >>> Q.put(4)         
7         Q.get()        

一、迭代器

对于Python 列表的 for 循环,他的内部原理:查看下一个元素是否存在,如果存在,则取出,如果不存在,则报异常 StopIteration。(python内部对异常已处理)

listiterator

二、生成器

range不是生成器 而 xrange 是生成器

readlines不是生成器 而 xreadlines 是生成器

1 >>> print range(10) 
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
3 >>> print xrange(10) 
4 xrange(10)

生成器内部基于yield创建,即:对于生成器只有使用时才创建,从而不避免内存浪费

练习:有如下列表: 
    [13, 22, 6, 99, 11] 
  
请按照一下规则计算: 
1322 比较,将大的值放在右侧,即:[13, 22, 6, 99, 11] 
226 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11] 
2299 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11] 
9942 比较,将大的值放在右侧,即:[13, 6, 22, 11, 99,] 
  
136 比较,将大的值放在右侧,即:[6, 13, 22, 11, 99,] 
...

解析:
li = [13, 22, 6, 99, 11] 
 
for m in range(len(li)-1): 
 
    for n in range(m+1, len(li)): 
        if li[m]> li[n]: 
            temp = li[n] 
            li[n] = li[m] 
            li[m] = temp 
 
print li
 

让a和b的值互换位置:

 1 >>> a = 123 
 2 >>> b = 321 
 3 >>> a,b 
 4 (123, 321) 
 5 >>> temp = a 
 6 >>> temp 
 7 123 
 8 >>> a = b 
 9 >>> a 
10 321 
11 >>> b = temp 
12 >>> a,b 
13 (321, 123) 
14 >>>
评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Centos7 中lvs DR配置