Python基础知识02-数据类型与变量

Python 变量类型

一:声明变量

  变量就是代表某个数据(值)的名称。python是一种动态类型语言,在赋值的执行中可以绑定不同类型的值,这个过程叫做变量赋值,赋值同时确定了变量类型。

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

#!/usr/bin/env python
#_*_ coding:utf-8 _*_

name = 'amonos'
print name

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

二:变量的定义规则

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

以下关键字不能声明为变量名

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

三:变量赋值

  • 链式赋值:a = b = c = 1(创建一个整型对象,值为1,三个变量被分配到相同的内存空间上。)
  • 多元赋值:a, b, c = 1, 2, "john"(两个整型对象1和2的分配给变量 a 和 b,字符串对象 "john" 分配给变量 c。)
  • 增量/减量/乘量/除量 赋值:a +=1; a -=1; a *=1;  a /=1
name1 = "wupeiqi"
name2 = "alex"

name1 = "wupeiqi"
name2 = name1

Python 运算符

一、算数运算符

二、比较运算

三、赋值运算

四、逻辑运算

五、成员运算

六、身份运算

七、位运算

#!/usr/bin/python
 
a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0
 
c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c
 
c = a | b;        # 61 = 0011 1101
print "Line 2 - Value of c is ", c
 
c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c
 
c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c
 
c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c
 
c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", 
位运算示例

八、运算符优先级

Python数据类型

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

一、数据类型分类:

1、数字

int(整型)

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

python2.*

  • 在32位机器上,整数的位数为32位,取值范围为-2^31~2^31-1,即-2147483648~2147483647
  • 在64位系统上,整数的位数为64位,取值范围为-2^63~2^63-1,即-9223372036854775808~9223372036854775807
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)
    """
    def bit_length(self): 
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        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)
        # (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
python 2.*

python3.*:整形长度无限制

class int(object):
    """
    int(x=0) -> integer
    int(x, base=10) -> integer
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is a number, return x.__int__().  For floating point
    numbers, this truncates towards zero.
    
    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance 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)
    """
    def bit_length(self): # real signature unknown; restored from __doc__
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回该复数的共轭复数 """
        """ Returns self, the complex conjugate of any int. """
        pass

    @classmethod # known case
    def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.from_bytes(bytes, byteorder, *, signed=False) -> int
        
        Return the integer represented by the given array of bytes.
        
        The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        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
        
        Return an array of bytes representing an integer.
        
        The integer is represented using length bytes.  An OverflowError is
        raised if the integer is not representable with the given number of
        bytes.
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument determines whether two's complement is
        used to represent the integer.  If signed is False and a negative integer
        is given, an OverflowError is raised.
        """
        pass

    def __abs__(self, *args, **kwargs): # real signature unknown
        """ abs(self) """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

    def __bool__(self, *args, **kwargs): # real signature unknown
        """ self != 0 """
        pass

    def __ceil__(self, *args, **kwargs): # real signature unknown
        """
        整数返回自己
        如果是小数
         math.ceil(3.1)返回4
        """
        """ Ceiling of an Integral returns itself. """
        pass

    def __divmod__(self, *args, **kwargs): # real signature unknown
        """ 相除,得到商和余数组成的元组 """
        """ Return divmod(self, value). """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __float__(self, *args, **kwargs): # real signature unknown
        """ float(self) """
        pass

    def __floordiv__(self, *args, **kwargs): # real signature unknown
        """ Return self//value. """
        pass

    def __floor__(self, *args, **kwargs): # real signature unknown
        """ Flooring an Integral returns itself. """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __index__(self, *args, **kwargs): # real signature unknown
        """ 用于切片,数字无意义 """
        """ Return self converted to an integer, if self is suitable for use as an index into a list. """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance 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)
        # (copied from class doc)
        """
        pass

    def __int__(self, *args, **kwargs): # real signature unknown

        """ int(self) """
        pass

    def __invert__(self, *args, **kwargs): # real signature unknown
        """ ~self """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lshift__(self, *args, **kwargs): # real signature unknown
        """ Return self<<value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __neg__(self, *args, **kwargs): # real signature unknown
        """ -self """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __pos__(self, *args, **kwargs): # real signature unknown
        """ +self """
        pass

    def __pow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(self, value, mod). """
        pass

    def __radd__(self, *args, **kwargs): # real signature unknown
        """ Return value+self. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

    def __rdivmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(value, self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __rfloordiv__(self, *args, **kwargs): # real signature unknown
        """ Return value//self. """
        pass

    def __rlshift__(self, *args, **kwargs): # real signature unknown
        """ Return value<<self. """
        pass

    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return value*self. """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __round__(self, *args, **kwargs): # real signature unknown
        """
        Rounding an Integral returns itself.
        Rounding with an ndigits argument also returns an integer.
        """
        pass

    def __rpow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(value, self, mod). """
        pass

    def __rrshift__(self, *args, **kwargs): # real signature unknown
        """ Return value>>self. """
        pass

    def __rshift__(self, *args, **kwargs): # real signature unknown
        """ Return self>>value. """
        pass

    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass

    def __rtruediv__(self, *args, **kwargs): # real signature unknown
        """ Return value/self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Returns size in memory, in bytes """
        pass

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass

    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass

    def __truediv__(self, *args, **kwargs): # real signature unknown
        """ Return self/value. """
        pass

    def __trunc__(self, *args, **kwargs): # real signature unknown
        """ Truncating an Integral returns itself. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        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"""

python3.5
python3.*

long(长整型)

  python2.*:跟C语言不同,Python的长整型没有指定位宽,也就是说Python没有限制长整型数值的大小,但是实际上由于机器内存有限,所以我们使用的长整型数值不可能无限大。在使用过程中,我们如何区分长整型和整型数值呢?

  通常的做法是在数字尾部加上一个大写字母L或小写字母l以表示该整数是长整型的,例如:
  a = 9223372036854775808L
注意,自从Python2起,如果发生溢出,Python会自动将整型数据转换为长整型,所以如今在长整型数据后面不加字母L也不会导致严重后果了。
  python3.*:长整型,整型统一归为整型

2、布尔值

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

3:浮点数

  浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x10^9和12.3x10^8是完全相等的。浮点数可以用数学写法,如1.23,3.14,-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23x10^9就是1.23e9,或者12.3e8,0.000012可以写成1.2e-5,等等。
  整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差。

4:复数

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

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

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

二、字符串

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

特性:

  • 只能存放一个值
  • 不可变
  • 按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

1、字符串创建

a='hello word'
注:单引号和双引号没有任何区别

2、字符串的常用方法

  移除空白、分割、长度、索引、切片

name = "amonos"
print name.capitalize()     # 首字母变成大写

msg = 'hello world'
print msg.count('l')        # 统计出现l在msg中出现的次数
print msg.count('l', 0, 3)  # 统计l在msg中0到3之间l出现的次数
print msg.count('l', -1)    # 统计l在msg中最后一个字符中出现l的次数
print msg.endswith('s')     # 判断msg是不是以s结尾,不是则为False,是为True
print msg.startswith('h')   # 判断msg是不是以h开头,不是则为False,是为True
print msg.find('l')         # 统计l出现的位置,如果不存在,则返回-1,存在返回位置,存在多个,只返回第一个出现的位置
print msg.find('l', 3, 9)   # 统计l在msg的3到9之间,l出现的位置
print msg.index('e')        # index与find本质区别是:index已经知道msg中存在e,然后进行查找,如果不存在会报错。
print msg.isdigit()         # 判断字符串中是否包含数字,包含数字为False,不包含为True

msg = 'hello world'         # 多用于字符串拼接
msg_new = '*'.join(msg)
print msg_new

msg = 'root:x:0:0:root:/bin/bash'
print msg.split(':')                # split分割
print msg.split(':', maxsplit=1)    # 以:为分割符,最大分割一次

msg_list = msg.split(':')
print(':'.join(msg_list))           # 按照:拼接字符串

msg = 'helLo world'
print msg.upper()                   # 小写转化为大写
print msg.swapcase()                # 大小写转换

msg = '*****yyp*****'
print msg.strip('*')    # 去掉首尾的指定字符
print msg.lstrip('*')   # 去除左边指定字符
print msg.rstrip('*')   # 去除右边指定字符

print msg.replace('z', 'y')  # 替换字符,不指定个数全部替换,指定几个就替换几个
print msg.replace('y', 'p', 1)

3、字符串不常用的方法

# 不常用的方法
msg = 'hello world'
print msg.isalpha()         # msg是纯字母返回True,不是则返回False
print msg.isidentifier()    # msg是内置标识符,返回True,否则返回False
print msg.isspace()         # msg是空格,返回True,反之,返回False
print msg.istitle()         # msg是标题,也就是首字母大写,返回True
print msg.ljust(10)         # 10个字符左对齐
print msg.ljust(10, '*')    # 10个字符左对齐,10个字符*填充
print msg.rjust(10)         # 10个字符右对齐
print msg.rjust(10, '*')    # 10个字符右对齐,10个字符*填充
print msg.zfill(20)         # 总长度20个,不足则在右边添加0
print name.center(30)       # 居中
print name.center(30, '*')  # 居中加填充

message = '''aaa
bbb
ccc
ddd
'''
print message.splitlines()  # 按照行数切分

4、字符串工厂函数

class str(object):
    """
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
 
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    """
    def capitalize(self): # real signature unknown; restored from __doc__
        """
        首字母变大写
        S.capitalize() -> str
 
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""
 
    def casefold(self): # real signature unknown; restored from __doc__
        """
        S.casefold() -> str
 
        Return a version of S suitable for caseless comparisons.
        """
        return ""
 
    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        原来字符居中,不够用空格补全
        S.center(width[, fillchar]) -> str
 
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""
 
    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
         从一个范围内的统计某str出现次数
        S.count(sub[, start[, end]]) -> int
 
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0
 
    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        encode(encoding='utf-8',errors='strict')
        以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是
        ignore或replace
 
        S.encode(encoding='utf-8', errors='strict') -> bytes
 
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""
 
    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
 
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False
 
    def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        将字符串中包含的\t转换成tabsize个空格
        S.expandtabs(tabsize=8) -> str
 
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""
 
    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
 
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
 
        Return -1 on failure.
        """
        return 0
 
    def format(self, *args, **kwargs): # known special case of str.format
        """
        格式化输出
        三种形式:
        形式一.
        >>> print('{0}{1}{0}'.format('a','b'))
        aba
 
        形式二:(必须一一对应)
        >>> print('{}{}{}'.format('a','b'))
        Traceback (most recent call last):
          File "<input>", line 1, in <module>
        IndexError: tuple index out of range
        >>> print('{}{}'.format('a','b'))
        ab
 
        形式三:
        >>> print('{name} {age}'.format(age=12,name='lhf'))
        lhf 12
 
        S.format(*args, **kwargs) -> str
 
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass
 
    def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        与format区别
        '{name}'.format(**dict(name='alex'))
        '{name}'.format_map(dict(name='alex'))
 
        S.format_map(mapping) -> str
 
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""
 
    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
 
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0
 
    def isalnum(self): # real signature unknown; restored from __doc__
        """
        至少一个字符,且都是字母或数字才返回True
 
        S.isalnum() -> bool
 
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isalpha(self): # real signature unknown; restored from __doc__
        """
        至少一个字符,且都是字母才返回True
        S.isalpha() -> bool
 
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool
 
        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False
 
    def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool
 
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isidentifier(self): # real signature unknown; restored from __doc__
        """
        字符串为关键字返回True
 
        S.isidentifier() -> bool
 
        Return True if S is a valid identifier according
        to the language definition.
 
        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False
 
    def islower(self): # real signature unknown; restored from __doc__
        """
        至少一个字符,且都是小写字母才返回True
        S.islower() -> bool
 
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
 
    def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool
 
        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False
 
    def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
 
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False
 
    def isspace(self): # real signature unknown; restored from __doc__
        """
        至少一个字符,且都是空格才返回True
        S.isspace() -> bool
 
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def istitle(self): # real signature unknown; restored from __doc__
        """
        >>> a='Hello'
        >>> a.istitle()
        True
        >>> a='HellP'
        >>> a.istitle()
        False
 
        S.istitle() -> bool
 
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False
 
    def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool
 
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
 
    def join(self, iterable): # real signature unknown; restored from __doc__
        """
        #对序列进行操作(分别使用' '与':'作为分隔符)
        >>> seq1 = ['hello','good','boy','doiido']
        >>> print ' '.join(seq1)
        hello good boy doiido
        >>> print ':'.join(seq1)
        hello:good:boy:doiido
 
 
        #对字符串进行操作
 
        >>> seq2 = "hello good boy doiido"
        >>> print ':'.join(seq2)
        h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
 
 
        #对元组进行操作
 
        >>> seq3 = ('hello','good','boy','doiido')
        >>> print ':'.join(seq3)
        hello:good:boy:doiido
 
 
        #对字典进行操作
 
        >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
        >>> print ':'.join(seq4)
        boy:good:doiido:hello
 
 
        #合并目录
 
        >>> import os
        >>> os.path.join('/hello/','good/boy/','doiido')
        '/hello/good/boy/doiido'
 
 
        S.join(iterable) -> str
 
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""
 
    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str
 
        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
 
    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
 
        Return a copy of the string S converted to lowercase.
        """
        return ""
 
    def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str
 
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().
 
        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass
 
    def partition(self, sep): # real signature unknown; restored from __doc__
        """
        以sep为分割,将S分成head,sep,tail三部分
 
        S.partition(sep) -> (head, sep, tail)
 
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass
 
    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
 
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
 
    def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int
 
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
 
        Return -1 on failure.
        """
        return 0
 
    def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int
 
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0
 
    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str
 
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
 
    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)
 
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass
 
    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings
 
        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []
 
    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str
 
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,
        如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
        >>> a='a,b c\nd\te'
        >>> a.split()
        ['a,b', 'c', 'd', 'e']
        S.split(sep=None, maxsplit=-1) -> list of strings
 
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []
 
    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        Python splitlines() 按照行('\r', '\r\n', \n')分隔,
        返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如        果为 True,则保留换行符。
        >>> x
        'adsfasdf\nsadf\nasdf\nadf'
        >>> x.splitlines()
        ['adsfasdf', 'sadf', 'asdf', 'adf']
        >>> x.splitlines(True)
        ['adsfasdf\n', 'sadf\n', 'asdf\n', 'adf']
 
        S.splitlines([keepends]) -> list of strings
 
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []
 
    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
 
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False
 
    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str
 
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def swapcase(self): # real signature unknown; restored from __doc__
        """
        大小写反转
        S.swapcase() -> str
 
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""
 
    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
 
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
 
    def translate(self, table): # real signature unknown; restored from __doc__
        """
        table=str.maketrans('alex','big SB')
 
        a='hello abc'
        print(a.translate(table))
 
        S.translate(table) -> str
 
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""
 
    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
 
        Return a copy of S converted to uppercase.
        """
        return ""
 
    def zfill(self, width): # real signature unknown; restored from __doc__
        """
        原来字符右对齐,不够用0补齐
         
        S.zfill(width) -> str
 
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""
 
    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass
 
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass
 
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
 
    def __format__(self, format_spec): # real signature unknown; restored from __doc__
        """
        S.__format__(format_spec) -> str
 
        Return a formatted version of S as described by format_spec.
        """
        return ""
 
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
 
    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass
 
    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass
 
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
 
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
 
    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass
 
    def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
        """
        str(object='') -> str
        str(bytes_or_buffer[, encoding[, errors]]) -> str
 
        Create a new string object from the given object. If encoding or
        errors is specified, then the object must expose a data buffer
        that will be decoded using the given encoding and error handler.
        Otherwise, returns the result of object.__str__() (if defined)
        or repr(object).
        encoding defaults to sys.getdefaultencoding().
        errors defaults to 'strict'.
        # (copied from class doc)
        """
        pass
 
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
 
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
 
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
 
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
 
    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value. """
        pass
 
    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass
 
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
 
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
 
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
 
    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass
 
    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass
 
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass
 
    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass
string

5、字符串索引,再看解压:

# 字符串索引操作
msg = 'hello'
print msg[4]
print msg[-2]
# 字符串的切分操作
print msg[0:3]          # 切分原则:顾头不顾尾
print msg[0:] 
print msg[:3]
print msg[0:2000:2]     # 按两个字符切分
print msg[::-1]         # hello倒过来

# 再看变量解压操作
msg = 'hello'
x, y, z, *_ = msg
print x
print y
print z
x, y, z = 'abc', 'aaa', 'xxx'
print x
print y
print z

三、列表

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

特性:

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

1、列表的创建

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

2、列表常用方法

  索引、切片、追加、删除、长度、切片、循环包含

name_list = ['a', 'b', 'c', 'd']
# 列表的索引操作
print name_list[-1]
print name_list[0:2]
print name_list[::-1]

# 列表的内置方法
name_list = ['a','b']
name_list.append('c')       # append增加到末尾
name_list.insert(0, 'd')    # insert插入到指定位置
name_list.pop(2)            # 指定删除第二个# pop删除name_list.pop()#默认从右边删除
name_list.clear()           # 清空列表
name_list.count('a')        # 统计a出现的次数
name_list.remove('a')       # remove移除,按照元素名移除,有多个重复的元素值时,移除第一个
name_list.reverse()         # reverse反序排列
name_list.sort()            # 使用list.sort()方法来排序,仅被定义在list,按照字符编码表排列
name_list.sortd()           # 使用list.sort()方法来排序,对所有的可迭代序列都有效
len(name_list)              # 统计列表有几个元素或说成列表的长度
print  'a' in name_list     # 判断是否在列表里面

import copy
n = name_list.copy()        # 浅复制一份copy,浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
n = copy.copy(name_list)    # 浅复制一份copy
n = copy.deepcopy(name_list)# 深复制一份copy,深拷贝 拷贝对象及其子对象

name_list = ['a', 'b']
nlist = ['c']
name_list.extend(nlist)     # 两个列表合并

every_lis = 'xxx'
name_list.extend(every_lis) # 单独加入列表

3、列表工厂函数

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass
 
    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass
 
    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []
 
    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0
 
    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass
 
    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0
 
    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass
 
    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass
 
    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass
 
    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass
 
    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass
 
    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass
 
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass
 
    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass
 
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
 
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
 
    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass
 
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
 
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
 
    def __iadd__(self, *args, **kwargs): # real signature unknown
        """ Implement self+=value. """
        pass
 
    def __imul__(self, *args, **kwargs): # real signature unknown
        """ Implement self*=value. """
        pass
 
    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass
 
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
 
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
 
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
 
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
 
    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass
 
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
 
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
 
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
 
    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass
 
    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass
 
    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass
 
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass
 
    __hash__ = None
List

四、元组

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

特性:

  1. 可以存多个值

  2. 不可变

  3. 按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

1、元组的创建

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

2、元组的常用方法

  索引、切片、循环、长度、包含

t=('a','b',123)
f=('a','B')
t.count('sy')       #统计sy的次数
t.index('sy')       #统计sy的索引,没有则报错
len(t)              #统计元组的长度
print 'sy' in t     #包含,t是否包含sy

#内置函数
cmp(tuple1, tuple2):比较两个元组元素。
len(tuple):计算元组元素个数。
max(tuple):返回元组中元素最大值。
min(tuple):返回元组中元素最小值。
tuple(seq):将列表转换为元组。

3、元组的工厂函数

lass 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.
        """
        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
 
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ T.__sizeof__() -- size of T in memory, in bytes """
        pass
tuple

4、元组的不可变行

t = ('yyp', 'sy', ['YYP', 'SY'])
print t
t[2][0] = 'Y'
t[2][1] = 'S'
print t
#输出信息:
('yyp', 'sy', ['YYP', 'SY'])
('yyp', 'sy', ['Y', 'S'])

五、字典

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

特性:

  1. 可存放多个值
  2. 可修改指定key对应的值,可变
  3. 无序
  4. 可变类型不能当做字典的key,value可以是任何数据类型
  5. key不能重复

1、字典的创建

dic={'name1':'yyp','name2':'sy'}
dic1={(1,2,3):'aa'} #元组可以当做key
dic2 = dict(name='yyp', age=16)
dic3 = dict({"name": "yyp", 'age': 28})
dic4 = dict((['name','yyp'],['age',120]))
 
输出结果:
{'name1': 'yyp', 'name2': 'sy'}
{(1, 2, 3): 'aa'}
{'name': 'yyp', 'age': 16}
{'name': 'yyp', 'age': 28}
{'name': 'yyp', 'age': 20}

2、字典的常用方法

  索引、新增、删除、键、值、键值对、循环、长度

info={'msg1':'yyp','msg2':'sy','msg3':'yp','msg4':'yy'}
print 'msg1' in info        #标准用法,存在返回True,不存在返回False
print info.get('msg2')      #获取value
print info.get('msg8')      #key不存在不会报错,返回None
print info['msg2']          #获取的到的时候,取值
print info['msg8']          #找不到key,则报错
info['msg4'] = 'yp'         #增加
info['msg2'] = 'yy'         #修改
info.pop('msg3')            #删除'msg3'
del info['msg2']            #删除'msg2'
info.popitem()              #随机删除一个
info.clear()                #整个列表清空

3、字典的其他操作:

多级字典嵌套:

#!/usr/bin/env python
#_*_ coding:utf-8 _*_

dict_name = {
    "msg1":{
        "name1": ["","one"],
        "name2": ["","two"],
    },
    "msg2":{
        "name3":["li","whree"]
    },
    "msg3":{
        "name4":["","four"]
    }
}
 
dict_name["msg2"]["name3"][1] += ",你好"
print dict_name["msg2"]["name3"]
 
#输出结果:
['li', 'whree,你好']

4、字典的工厂函数

class dict(object):
    """
    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)
    """
 
    def clear(self): # real signature unknown; restored from __doc__
        """ 清除内容 """
        """ D.clear() -> None.  Remove all items from D. """
        pass
 
    def copy(self): # real signature unknown; restored from __doc__
        """ 浅拷贝 """
        """ D.copy() -> a shallow copy of D """
        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.
        """
        pass
 
    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根据key获取值,d是默认值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass
 
    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False
 
    def items(self): # real signature unknown; restored from __doc__
        """ 所有项的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []
 
    def iteritems(self): # real signature unknown; restored from __doc__
        """ 项可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass
 
    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass
 
    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass
 
    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D's keys """
        return []
 
    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.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
        """
        pass
 
    def popitem(self): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass
 
    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass
 
    def update(self, E=None, **F): # known special case of dict.update
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k in F: D[k] = F[k]
        """
        pass
 
    def values(self): # real signature unknown; restored from __doc__
        """ 所有的值 """
        """ D.values() -> list of D's values """
        return []
 
    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有项,只是将内容保存至view对象中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass
 
    def viewkeys(self): # real signature unknown; restored from __doc__
        """ D.viewkeys() -> a set-like object providing a view on D's keys """
        pass
 
    def viewvalues(self): # real signature unknown; restored from __doc__
        """ D.viewvalues() -> an object providing a view on D's values """
        pass
 
    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass
 
    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False
 
    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        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 __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)
        # (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
 
    @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 __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass
 
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass
 
    __hash__ = None
Dictionary

六、集合

1、集合的创建

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

2、集合的常用操作

msg = set([1, 1, 2, 2, 3, 3])   #重复的元素自动过滤掉
msg.add(8)                      #可以添加元素到set中,可以重复添加,但是没有任何效果哦
msg.remove(1)                   #删除set中的元素
msg.update([5,8,6])             #在set中添加多项
len(msg))                       #set的长度

3、set关系运算

msg1 = set([2, 3, 5, 6, 8])
msg2 = set([1,3,5])
print 1 in msg1     #测试1是否是msg1的成员,是则返回True,否则返回False
print(1 not in msg1) #测试1是否不是msg1的成员,是则返回False,不是返回True
#测试是否msg2中的每一个元素都在msg1中
print msg2.issubset(msg1)
print msg2 <= msg1 
#返回一个新的set包含msg1和msg2的每一个元素
print msg2.union(msg1)
print msg2 | msg1
#输出结果:
{1, 2, 3, 5, 6, 8}
{1, 2, 3, 5, 6, 8} 
#返回一个新的set包含msg1与msg2的公共元素
print msg2.intersection(msg1)
print msg1 & msg2
#输出结果:
{3, 5}
{3, 5}
#返回一个新的set包含msg2中有但是msg1中没有的元素
print msg2.difference(msg1)
print msg2 - msg1
#输出结果:
{1}
{1} 
#返回一个新的set包含msg2和msg1中不重复的元素
print msg2.symmetric_difference(msg1)
print msg2 ^ msg1
#输出结果:
{1, 2, 6, 8}
{1, 2, 6, 8}
#返回set “msg1”的一个浅的复制
print msg1.copy()
#输出结果:
{8, 2, 3, 5, 6}

4、set做交集、并集等操作

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

5、集合工厂

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
     
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set.
         
        This has no effect if the element is already present.
        """
        pass
 
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass
 
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass
 
    def difference(self, *args, **kwargs): # real signature unknown
        """
        相当于s1-s2
         
        Return the difference of two or more sets as a new set.
         
        (i.e. all elements that are in this set but not the others.)
        """
        pass
 
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set. """
        pass
 
    def discard(self, *args, **kwargs): # real signature unknown
        """
        与remove功能相同,删除元素不存在时不会抛出异常
         
        Remove an element from a set if it is a member.
         
        If the element is not a member, do nothing.
        """
        pass
 
    def intersection(self, *args, **kwargs): # real signature unknown
        """
        相当于s1&s2
         
        Return the intersection of two sets as a new set.
         
        (i.e. all elements that are in both sets.)
        """
        pass
 
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass
 
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass
 
    def issubset(self, *args, **kwargs): # real signature unknown
        """
        相当于s1<=s2
         
        Report whether another set contains this set. """
        pass
 
    def issuperset(self, *args, **kwargs): # real signature unknown
        """
        相当于s1>=s2
         
         Report whether this set contains another set. """
        pass
 
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass
 
    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.
         
        If the element is not a member, raise a KeyError.
        """
        pass
 
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        相当于s1^s2
         
        Return the symmetric difference of two sets as a new set.
         
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
 
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        pass
 
    def union(self, *args, **kwargs): # real signature unknown
        """
        相当于s1|s2
         
        Return the union of sets as a new set.
         
        (i.e. all elements that are in either set.)
        """
        pass
 
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        pass
 
    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass
 
    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass
 
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
 
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
 
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
 
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
 
    def __iand__(self, *args, **kwargs): # real signature unknown
        """ Return self&=value. """
        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)
        """
        pass
 
    def __ior__(self, *args, **kwargs): # real signature unknown
        """ Return self|=value. """
        pass
 
    def __isub__(self, *args, **kwargs): # real signature unknown
        """ Return self-=value. """
        pass
 
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
 
    def __ixor__(self, *args, **kwargs): # real signature unknown
        """ Return self^=value. """
        pass
 
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
 
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
 
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
 
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
 
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
 
    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass
 
    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass
 
    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass
 
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
 
    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass
 
    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass
 
    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass
 
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass
 
    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass
 
    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass
 
    __hash__ = None
set 

七、collection系列

1、计数器(couter)

  Counter是对字典类型的补充,用于追踪值的出现次数。ps:具备字典的所有功能 + 自己的功能

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

class Counter(dict):
    '''Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

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

    >>> c['a']                          # count of letter 'a'
    >>> 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'
    >>> del c['b']                      # remove all 'b'
    >>> c['b']                          # now there are zero 'b'

    >>> d = Counter('simsalabim')       # make another counter
    >>> c.update(d)                     # add in the second counter
    >>> c['a']                          # now there are nine 'a'

    >>> 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__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

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

        '''
        super(Counter, self).__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        """ 对于不存在的元素,返回计数器为0 """
        'The count of elements not in the Counter is zero.'
        # Needed so that self[missing_item] does not raise KeyError
        return 0

    def most_common(self, n=None):
        """ 数量从大到写排列,获取前N个元素 """
        '''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.iteritems(), key=_itemgetter(1), reverse=True)
        return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))

    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

        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.iteritems()))

    # 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(self, iterable=None, **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

        '''
        # 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 iterable is not None:
            if isinstance(iterable, Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    super(Counter, self).update(iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def subtract(self, iterable=None, **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
        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
        -1

        '''
        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)

    def copy(self):
        """ 拷贝 """
        'Return a shallow copy.'
        return self.__class__(self)

    def __reduce__(self):
        """ 返回一个元组(类型,元组) """
        return self.__class__, (dict(self),)

    def __delitem__(self, elem):
        """ 删除元素 """
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            super(Counter, self).__delitem__(elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # 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

    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

    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

    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
Counter

2、有序字典(orderedDict)

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

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).
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].

    def __init__(self, *args, **kwds):
        '''Initialize an ordered dictionary.  The signature is the same as
        regular dictionaries, but keyword arguments are not recommended because
        their insertion order is arbitrary.

        '''
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []                     # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
        '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:
            root = self.__root
            last = root[0]
            last[1] = root[0] = self.__map[key] = [last, root, key]
        return dict_setitem(self, key, value)

    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_prev, link_next, _ = self.__map.pop(key)
        link_prev[1] = link_next                        # update link_prev[NEXT]
        link_next[0] = link_prev                        # update link_next[PREV]

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        # Traverse the linked list in order.
        root = self.__root
        curr = root[1]                                  # start at the first node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[1]                              # move to next node

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        # Traverse the linked list in reverse order.
        root = self.__root
        curr = root[0]                                  # start at the last node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[0]                              # move to previous node

    def clear(self):
        'od.clear() -> None.  Remove all items from od.'
        root = self.__root
        root[:] = [root, root, None]
        self.__map.clear()
        dict.clear(self)

    # -- the following methods do not depend on the internal structure --

    def keys(self):
        'od.keys() -> list of keys in od'
        return list(self)

    def values(self):
        'od.values() -> list of values in od'
        return [self[key] for key in self]

    def items(self):
        'od.items() -> list of (key, value) pairs in od'
        return [(key, self[key]) for key in self]

    def iterkeys(self):
        'od.iterkeys() -> an iterator over the keys in od'
        return iter(self)

    def itervalues(self):
        'od.itervalues -> an iterator over the values in od'
        for k in self:
            yield self[k]

    def iteritems(self):
        'od.iteritems -> an iterator over the (key, value) pairs in od'
        for k in self:
            yield (k, self[k])

    update = MutableMapping.update

    __update = update # let subclasses override update without breaking __init__

    __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

    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

    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')
        key = next(reversed(self) if last else iter(self))
        value = self.pop(key)
        return key, value

    def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key]

    def __reduce__(self):
        'Return state information for pickling'
        items = [[k, self[k]] for k in self]
        inst_dict = vars(self).copy()
        for k in vars(OrderedDict()):
            inst_dict.pop(k, None)
        if inst_dict:
            return (self.__class__, (items,), inst_dict)
        return self.__class__, (items,)

    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

    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(_imap(_eq, self, other))
        return dict.__eq__(self, other)

    def __ne__(self, other):
        'od.__ne__(y) <==> od!=y'
        return not self == other

    # -- 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)

    def viewvalues(self):
        "od.viewvalues() -> an object providing a view on od's values"
        return ValuesView(self)

    def viewitems(self):
        "od.viewitems() -> a set-like object providing a view on od's items"
        return ItemsView(self)
OrderedDict

3、默认字典(orderedDict)

学前需求

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}
values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = {}

for value in  values:
    if value>66:
        if my_dict.has_key('k1'):
            my_dict['k1'].append(value)
        else:
            my_dict['k1'] = [value]
    else:
        if my_dict.has_key('k2'):
            my_dict['k2'].append(value)
        else:
            my_dict['k2'] = [value]
原生字典解决方法
from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)

for value in  values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
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.
    """
    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D. """
        pass

    def __copy__(self, *args, **kwargs): # real signature unknown
        """ D.copy() -> a shallow copy of D. """
        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

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """Factory for default value called by __missing__()."""
defaultdict

4、可命名元祖(namedtuple)

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

import collections
Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])
class Mytuple(__builtin__.tuple)
 |  Mytuple(x, y)
 |  
 |  Method resolution order:
 |      Mytuple
 |      __builtin__.tuple
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __getnewargs__(self)
 |      Return self as a plain tuple.  Used by copy and pickle.
 |  
 |  __getstate__(self)
 |      Exclude the OrderedDict from pickling
 |  
 |  __repr__(self)
 |      Return a nicely formatted representation string
 |  
 |  _asdict(self)
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  _replace(_self, **kwds)
 |      Return a new Mytuple object replacing specified fields with new values
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type
 |      Make a new Mytuple object from a sequence or iterable
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(_cls, x, y)
 |      Create new instance of Mytuple(x, y)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  x
 |      Alias for field number 0
 |  
 |  y
 |      Alias for field number 1
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  _fields = ('x', 'y')
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from __builtin__.tuple:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      T.__sizeof__() -- size of T in memory, in bytes
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
Mytuple

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

    def appendleft(self, *args, **kwargs): # real signature unknown
        """ Add an element to the left side of the deque. """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from the deque. """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ D.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, *args, **kwargs): # real signature unknown
        """ Extend the right side of the deque with elements from the iterable """
        pass

    def extendleft(self, *args, **kwargs): # real signature unknown
        """ Extend the left side of the deque with elements from the iterable """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ Remove and return the rightmost element. """
        pass

    def popleft(self, *args, **kwargs): # real signature unknown
        """ Remove and return the leftmost element. """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """ D.remove(value) -- remove first occurrence of value. """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ D.reverse() -- reverse *IN PLACE* """
        pass

    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

    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

    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 __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 __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

    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

    @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

    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

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    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

  注:既然有双向队列,也有单项队列(先进先出 FIFO )

class Queue:
    """Create a queue object with a given maximum size.

    If maxsize is <= 0, the queue size is infinite.
    """
    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

    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.
        """
        self.all_tasks_done.acquire()
        try:
            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
        finally:
            self.all_tasks_done.release()

    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.
        """
        self.all_tasks_done.acquire()
        try:
            while self.unfinished_tasks:
                self.all_tasks_done.wait()
        finally:
            self.all_tasks_done.release()

    def qsize(self):
        """Return the approximate size of the queue (not reliable!)."""
        self.mutex.acquire()
        n = self._qsize()
        self.mutex.release()
        return n

    def empty(self):
        """Return True if the queue is empty, False otherwise (not reliable!)."""
        self.mutex.acquire()
        n = not self._qsize()
        self.mutex.release()
        return n

    def full(self):
        """Return True if the queue is full, False otherwise (not reliable!)."""
        self.mutex.acquire()
        n = 0 < self.maxsize == self._qsize()
        self.mutex.release()
        return n

    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).
        """
        self.not_full.acquire()
        try:
            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()
        finally:
            self.not_full.release()

    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, False)

    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).
        """
        self.not_empty.acquire()
        try:
            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
        finally:
            self.not_empty.release()

    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(False)

    # 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, len=len):
        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.Queue

数据类型常用功能

一、数字和字符串深浅拷贝

  对于数字和字符串而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

#!/usr/bin/env python
#_*_ coding:utf-8 _*_

import copy

# ######### 数字、字符串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 赋值 ##
n2 = n1
print(id(n2))
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))

# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))

二、其他基本数据类型深浅拷贝

  对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。 

1、赋值: 只是创建一个变量,该变量指向原来内存地址,如:

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n2 = n1

2、浅拷贝:在内存中只额外创建第一层数据。

import copy

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n3 = copy.copy(n1)

3、深拷贝:在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

import copy
  
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n4 = copy.deepcopy(n1)

三、数据结构循环

#!/usr/bin/env python
#_*_ coding:utf-8 _*_




# !/usr/bin/env python
# _*_ coding:utf-8 _*_

# 字符串循环:
# 方法1:
msg = 'love'
for i in msg:
    print i
# 方法2:
for i in enumerate(msg):
    print i
# 结果:
(0, 'l')
(1, 'o')
(2, 'v')
(3, 'e')
# 方法3:倒叙循环
for i in msg[::-1]:
    print(i)

# 字典循环
info = {'msg1': 'yyp', 'msg2': 'sy', 'msg3': 'zl', 'msg4': 'yy'}
# 方法1
for key in info:
    print key, info[key]
# 结果
msg1
yyp
msg2
sy
msg3
zl
msg4
yy
# 方法2
for k, v in info.items():  # 会先把dict转成list,数据大时最好不要用
    print(k, v)

# 结果:
msg1
yyp
msg2
sy
msg3
zl
msg4
yy
# 方法3:
info = {'name1': 'yyp', 'name2': 'sy', 'name3': 'yy'}
for i in enumerate(info):
    print(i)
# 结果:
(0, 'name1')
(1, 'name2')
(2, 'name3')
# 方法4:
for i in info.keys():
    print(i, info[i])
# 结果:
name1
yyp
name2
sy
name3
yy

# 方法5:
for v in info.values():
    print(v)
# 结果:
yyp
sy
yy

#为可迭代的对象添加序号
li = [11,22,33]
for k,v in enumerate(li, 1):
    print(k,v)

#指定范围,生成指定的数字
print range(1, 10)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]

print range(1, 10, 2)
# 结果:[1, 3, 5, 7, 9]

print range(30, 0, -2)
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] 
数据结构循环方法

四、数据结构之间相互转换

元组和列表不可以转换成字典

nums=[1,3,5,7,8,0]
#列表转为字符串:
print str(nums),type(str(nums)) 
#列表转为元组:
print tuple(nums),type(tuple(nums))

tup=(1, 2, 3, 4, 5)
#元组转为字符串
print tup.__str__(),type(tup.__str__())
#元组转为列表
print list(tup),type(list(tup))

dic = {'name': 'Zara', 'age': 7, 'class': 'First'} 
#字典转为字符串
print str(dic),type(str(dic))
#字典可以转为元组
print tuple(dic),type(tuple(dic))
#字典可以转为元组
print tuple(dic.values()),type(tuple(dic.values()))
#字典转为列表
print list(dic),type(list(dic))
#字典转为列表
print list(dic.values()),type(list(dic.values())) 
#结果:
#{'age': 7, 'name': 'Zara', 'class': 'First'} <class 'str'>
#('age', 'name', 'class') <class 'tuple'>
#(7, 'Zara', 'First') <class 'tuple'>
#['age', 'name', 'class'] <class 'list'>
#[7, 'Zara', 'First'] <class 'list'>
数据结构之间相互转换

总结:

1、按存值个数区分

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

 

 

 

2、按可变不可变区分

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

 

 

 

证明:可变/不可变

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

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

3.按访问顺序区分

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

 

 

 

  

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

posted @ 2017-09-05 21:40  amonos  阅读(327)  评论(0编辑  收藏  举报