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

Python全栈之路---运算符与基本的数据结构

时间:2016-06-29 07:48:03      阅读:757      评论:0      收藏:0      [点我收藏+]

标签:

运算符

一、算术运算符:

技术分享

练习:

+    加法    两个对象相加    1 + 2得到3;‘a‘ + ‘b‘得到‘ab‘。
-    减法    一个数减去另一个数或者是负数    5 - 3得到2;-2得到一个负数
*    乘法    两个数相乘或者返回一个被重复若干次的字符串    -5.2得到一个负数。50 - 24得到26。
**    幂    返回x的y次幂    3 ** 4得到81(即3 * 3 * 3 * 3)
/    除    x除以y    4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333
//    取整除    返回商的整数部分    4 // 3.0得到1.0
%    取模    返回除法的余数    8%3得到2。-25.5%2.25得到1.5

二、比较运算符

技术分享

<<    左移    把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1)    2 << 2得到8。——2按比特表示为10
>>    右移    把一个数的比特向右移一定数目    11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。
~    按位翻转    x的按位翻转是-(x+1)    ~5得到-6
<    小于    返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写    5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True
>    大于    返回x是否大于y    5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。
<=    小于等    返回x是否小于等于y    x = 3; y = 6; x <= y返回True
==    等于    比较对象是否相等    x = 2; y = 2; x == y返回True。x = ‘str‘; y = ‘stR‘; x == y返回False。x = ‘str‘; y = ‘str‘; x == y返回True。
!=    不等于    比较两个对象是否不相等    x = 2; y = 3; x != y返回True

三、赋值运算符:

技术分享

四、逻辑运算符:

技术分享

not    布尔“非”    如果x为True,返回False。如果x为False,它返回True。    x = True; not x返回False
and    布尔“与”    如果x为False,x and y返回False,否则它返回y的计算值    x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。
or    布尔“或”    如果x是True,它返回True,否则它返回y的计算值。 x = True; y = False; x or y返回True。短路计算在这里也适用。   

五、成员运算符:

技术分享

六、身份运算:

技术分享

基本数据类型:

技术分享

一、整型(数字):int

Python可以处理任意大小的正负整数,但是实际中跟我们计算机的内存有关,在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1。

a=4
print(a.bit_length()) # 4在二进制中可以用最少3位 100 来表示4,所以输出3 
print(int(‘4‘))       #将字符串4转换成整数4 
  
# int还可下面的将二进制的字符串转换成整数, base=2 代表前面的字符串是二进制。 
print(int(‘1010‘,base=2)) # 输出10 
技术分享
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

二、长整型(long):

可能如:2147483649、9223372036854775807

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

技术分享
class long(object):
    """
    long(x=0) -> long
    long(x, base=10) -> long
    
    Convert a number or string to a long integer, or return 0L if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    
    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int(‘0b100‘, base=0)
    4L
    """
    def bit_length(self): # real signature unknown; restored from __doc__
        """
        long.bit_length() -> int or long
        
        Number of bits necessary to represent self in binary.
        >>> bin(37L)
        ‘0b100101‘
        >>> (37L).bit_length()

        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ Returns self, the complex conjugate of any long. """
        pass

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

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y): # real signature unknown; restored from __doc__
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y): # real signature unknown; restored from __doc__
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y): # real signature unknown; restored from __doc__
        """ x.__div__(y) <==> x/y """
        pass

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

    def __floordiv__(self, y): # real signature unknown; restored from __doc__
        """ x.__floordiv__(y) <==> x//y """
        pass

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

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

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

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

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

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

    def __init__(self, x=0): # real signature unknown; restored from __doc__
        pass

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

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

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

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

    def __mod__(self, y): # real signature unknown; restored from __doc__
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y): # real signature unknown; restored from __doc__
        """ x.__mul__(y) <==> x*y """
        pass

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

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

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

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

    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass

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

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

    def __radd__(self, y): # real signature unknown; restored from __doc__
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y): # real signature unknown; restored from __doc__
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y): # real signature unknown; restored from __doc__
        """ x.__rdiv__(y) <==> y/x """
        pass

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

    def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
        """ x.__rfloordiv__(y) <==> y//x """
        pass

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

    def __rmod__(self, y): # real signature unknown; restored from __doc__
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y): # real signature unknown; restored from __doc__
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass

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

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

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

    def __rsub__(self, y): # real signature unknown; restored from __doc__
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y): # real signature unknown; restored from __doc__
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass

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

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

    def __sub__(self, y): # real signature unknown; restored from __doc__
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y): # real signature unknown; restored from __doc__
        """ x.__truediv__(y) <==> x/y """
        pass

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

    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the real part of a complex number"""
long

三、浮点型(float):

如:3.14、2.88

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

技术分享
class float(object):
    """
    float(x) -> floating point number
    
    Convert a string or number to a floating point number, if possible.
    """
    def as_integer_ratio(self):   
        """ 获取改值的最简比 """
        """
        float.as_integer_ratio() -> (int, int)

        Return a pair of integers, whose ratio is exactly equal to the original
        float and with a positive denominator.
        Raise OverflowError on infinities and a ValueError on NaNs.

        >>> (10.0).as_integer_ratio()
        (10, 1)
        >>> (0.0).as_integer_ratio()
        (0, 1)
        >>> (-.25).as_integer_ratio()
        (-1, 4)
        """
        pass

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ Return self, the complex conjugate of any float. """
        pass

    def fromhex(self, string):   
        """ 将十六进制字符串转换成浮点型 """
        """
        float.fromhex(string) -> float
        
        Create a floating-point number from a hexadecimal string.
        >>> float.fromhex(‘0x1.ffffp10‘)
        2047.984375
        >>> float.fromhex(‘-0x1p-1074‘)
        -4.9406564584124654e-324
        """
        return 0.0

    def hex(self):   
        """ 返回当前值的 16 进制表示 """
        """
        float.hex() -> string
        
        Return a hexadecimal representation of a floating-point number.
        >>> (-0.1).hex()
        ‘-0x1.999999999999ap-4‘
        >>> 3.14159.hex()
        ‘0x1.921f9f01b866ep+1‘
        """
        return ""

    def is_integer(self, *args, **kwargs): # real signature unknown
        """ Return True if the float is an integer. """
        pass

    def __abs__(self):   
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):   
        """ x.__add__(y) <==> x+y """
        pass

    def __coerce__(self, y):   
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y):   
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y):   
        """ x.__div__(y) <==> x/y """
        pass

    def __eq__(self, y):   
        """ x.__eq__(y) <==> x==y """
        pass

    def __float__(self):   
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y):   
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, format_spec):   
        """
        float.__format__(format_spec) -> string
        
        Formats the float according to format_spec.
        """
        return ""

    def __getattribute__(self, name):   
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

    def __getformat__(self, typestr):   
        """
        float.__getformat__(typestr) -> string
        
        You probably don‘t want to use this function.  It exists mainly to be
        used in Python‘s test suite.
        
        typestr must be ‘double‘ or ‘float‘.  This function returns whichever of
        ‘unknown‘, ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘ best describes the
        format of floating point numbers used by the C type named by typestr.
        """
        return ""

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

    def __ge__(self, y):   
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y):   
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self):   
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, x):   
        pass

    def __int__(self):   
        """ x.__int__() <==> int(x) """
        pass

    def __le__(self, y):   
        """ x.__le__(y) <==> x<=y """
        pass

    def __long__(self):   
        """ x.__long__() <==> long(x) """
        pass

    def __lt__(self, y):   
        """ x.__lt__(y) <==> x<y """
        pass

    def __mod__(self, y):   
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y):   
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self):   
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more):   
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y):   
        """ x.__ne__(y) <==> x!=y """
        pass

    def __nonzero__(self):   
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __pos__(self):   
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None):   
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y):   
        """ x.__radd__(y) <==> y+x """
        pass

    def __rdivmod__(self, y):   
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y):   
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self):   
        """ x.__repr__() <==> repr(x) """
        pass

    def __rfloordiv__(self, y):   
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rmod__(self, y):   
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y):   
        """ x.__rmul__(y) <==> y*x """
        pass

    def __rpow__(self, x, z=None):   
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rsub__(self, y):   
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y):   
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __setformat__(self, typestr, fmt):   
        """
        float.__setformat__(typestr, fmt) -> None
        
        You probably don‘t want to use this function.  It exists mainly to be
        used in Python‘s test suite.
        
        typestr must be ‘double‘ or ‘float‘.  fmt must be one of ‘unknown‘,
        ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘, and in addition can only be
        one of the latter two if it appears to match the underlying C reality.
        
        Override the automatic determination of C-level floating point type.
        This affects how floats are converted to and from binary strings.
        """
        pass

    def __str__(self):   
        """ x.__str__() <==> str(x) """
        pass

    def __sub__(self, y):   
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y):   
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs): # real signature unknown
        """ Return the Integral closest to x between 0 and x. """
        pass

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the imaginary part of a complex number"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the real part of a complex number"""
float

四、布尔值(bool):

真或假
1 或 0

五、字符串(str):

python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。
字符串格式化
字符串常用功能:
  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
技术分享
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__
        """  下面是详细参数: 
        子串:是要搜索的子串。

        开始:从该指数开始搜索。第一个字符从索引0开始。通过默认搜索引擎从索引0开始。

        结束:搜索从该指数结束。第一个字符从索引0开始。默认情况下,搜索结束,在最后一个索引。


        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__
        """ 编码 上面有介绍
        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__
        """  以 某个字符结束
          suffix -- 该参数可以是一个字符串或者是一个元素。

      start -- 字符串中的开始位置。

      end -- 字符中结束位置。

 

      返回值

 

      如果字符串含有指定的后缀返回True,否则返回False。



        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__
        """ 把tab转换成空格
        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__
        """
find(str, pos_start, pos_end)

解释:

  str:被查找“字串”

  pos_start:查找的首字母位置(从0开始计数。默认:0)

  pos_end: 查找的末尾位置(默认-1)

返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。



        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(*args, **kwargs): # known special case of str.format
        """  占位符  类似变量引用
      s = "print hell {0} ,age {1}"
      print(s.format(‘alex‘,19))


        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__
        """字符串格式化,动态参数,将函数式编程时细说
        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__
        """ #跟find类似但是 没有找到的话会报错。 而find是返回-1
        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__
        """ #判断是否是数字和字母
        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__
        """是否是字母 
        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__
        """
        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__
        """是否小写字母
        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__
        """是否是空格
        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__
        """ 是否是标题  字符串开头是大写 后面是小写
        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__
        """ 拼接 后面有例子

        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__
        """ 内容左对齐,右侧填充
    ljust()方法语法:

 

    str.ljust(width[, fillchar])

 

    参数

 

    width -- 指定字符串长度。

    fillchar -- 填充字符,默认为空格。

 

    返回值

 

    返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

 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__ """ 以指定 字符 开始分割 指定的字符也显示 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__ """ 替换
    old -- 将被替换的子字符串。

    new -- 新字符串,用于替换old子字符串。

    max -- 可选字符串, 替换不超过 max 次

    返回值

    返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。



        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__
        """ 从右侧开始分割 sep是指定几个
        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.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__
        """
        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__
        """


    转换,需要先做一个对应表,最后一个表示删除字符集合
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab)
    str = "this is string example....wow!!!"print str.translate(trantab, xm)




        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
官方文档str
s="abcdef ghg k"
print(s.title())              #将字符串转换成标题,输出 Abcdef Ghg K 
  
print(s.capitalize())         #将字符串首字母大写,输出 Abcdef ghg k 
  
print(s.count(‘d‘,0,len(s)))  #计算出子串 ‘d‘在母串中出现的次数,默认是在整个母串中查找, 
                  #可以在后面跟两个参数指定起始位置查找,这里我指定了在(0,len(s))中查找, 
                  #其中len(s)代表获取字符串长度 
  
print(s.startswith(‘a‘))      #判断字符串是否以什么开头,这里输出True, 
  
print(s.find(‘g‘,0,len(s)))   #查找子串第一次在母串中出现的位置,这里输出7,同样可以自己指定位置范围来搜查 
  
print(s.upper())              #将字符串转换成大写,这里输出ABCDEF GHG K 
  
print(s.join([‘a‘,‘b‘,‘c‘]))  #用字符串 s 来连接列表[‘a‘,‘b‘,‘c‘] 输出 aabcdef ghg kbabcdef ghg kc 
  
print(s.strip())         #移除两侧空格 
  
print(s.split())         #分割字符串,返回一个列表 这里输出[‘abcdef‘, ‘ghg‘, ‘k‘] 
  
print(s.replace(‘g‘,‘G‘,1))   #替换,默认全部替换,可以设置为1,只替换一次,这里只替换一次输出abcdef Ghg k 
  
print(s[0:4])                 #切片,[0:4]代表将字符串s的前面4位取出来,这里输出 abcd 

注:strip()

  1. 可以去除两端空格
  2. 可以去除末尾\n
  3. 可以去除空行
  4. n = "hello"

   s = n.strip("o")

   print(s)==>"hell"

六、列表(list)

列表的基本操作:

list = [‘Google‘, ‘baidu‘, ‘taobao‘]

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含
技术分享
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) -- append object to end """
        pass

    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) -- 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) -- 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, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    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 __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]
                   
                   Use of negative indices is not supported.
        """
        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 __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 __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        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): # 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 __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

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

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y
                   
                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None
list官方文档
l=[‘a‘,‘b‘,‘cc‘,4]     #定义一个列表 
  
l.append(5)         #添加一个元素,l=[‘a‘, ‘b‘, ‘cc‘, 4, 5] 
  
l.pop()           #从尾部删除一个元素,l=[‘a‘, ‘b‘, ‘cc‘, 4] 
  
l.remove(‘a‘)         #从列表中移除 ‘a‘,l=[‘b‘, ‘cc‘, 4] 
  
l.extend([‘gg‘,‘kk‘])    #添加一个列表[‘gg‘,‘kk‘], l=[‘b‘, ‘cc‘, 4, ‘gg‘, ‘kk‘] 
  
l.reverse()          #反转一个列表,l=[‘kk‘, ‘gg‘, 4, ‘cc‘, ‘b‘] 
  
print(l.count(‘kk‘))     #某元素出现的次数 输出 1 
  
print(l.index(‘gg‘))     #元素出现的位置,输出 1 
  
for i in l:          #循环输出列表元素 
    print(i) 
  
print(l[0:4:2])       #列表切片,以步长2递增,输出[‘kk‘, 4] 
技术分享列表的练习

七、元组(tuple)

元组是一个固定的不可变(元组一旦创建 不等增加也不能减少),tuple也是有序的,tuple使用的是小括号标识

基本操作:

  • 索引
  • 切片
  • 循环
  • 长度
  • 包含
技术分享
class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable‘s items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

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

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

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

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

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        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的官方文档
t=(‘a‘,‘b‘,‘b‘,‘c‘)   #定义一个元组 
  
print(t.index(‘b‘))   #索引出元素第一次出现的位置,还可以指定在某一范围里查找,这里默认在整个元组里查找输出1 
  
print(t.count(‘b‘))   #计算元素出现的次数,这里输出2 
  
print(len(t))      #输出远组的长度,这里输出4 
  
for i in t: 
    print(i)       #循环打印出元组数据 
  
print(t[1:3])       #切片 输出(‘b‘,‘b‘) 

元组的其他例子:

技术分享
############### 元组 #################
name_tuple = (alex, eric)
# 索引
print(name_tuple[0])
# len
print(name_tuple[len(name_tuple)-1])
# 切片
print(name_tuple[0:1])
# for
for i in name_tuple:
    print(i)
# 删除
# del name_tuple[0] 不支持
# count,计算元素出现的个数
print(name_tuple.count(alex))
# index 获取指定元素的索引位置
print(name_tuple.index(alex))
元组

八、字典 dict(无序的)

pc =  {‘host‘: ‘2.2.2.2‘, ‘port‘: 80]}

ps:循环时,默认循环key

常用操作:

  • 索引
  • 新增
  • 删除
  • 键、值、键值对
  • 循环
  • 长度
技术分享
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
dict的官方文档
d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85} 
  
d.get(‘Bob‘)                     #根据key获取values,如果不存在返回None,这里输出75 
  
d.pop(‘Bob‘)                     #根据键删除某一元素 d={‘Michael‘: 95, ‘Tracy‘: 85} 
  
d[‘Jason‘]=99                       #新增元素 d={‘Michael‘: 95, ‘Tracy‘: 85, ‘Jason‘: 99} 
  
print(len(d))                       #输出字典长度,这里输出3 
  
print(‘Jason‘ in d)                 #python3 中移除了 has_key,要判断键是否存在用in 
  
for i in d: 
    print(i)                     #循环默认按键输出 
  
for i in d.values():                #循环按值输出 
    print(i) 
  
for k,v in d.items():                #循环按键值输出 
    print(k,v) 
技术分享
value末尾不要忘记加逗号
contact = {
    222 : [dfas,fdas,hjgkj],
    gkgj : [dsfa,dsfa],
    3333 : [dsfa,dsfa],   
    324234 : [dsaf,fdasfsa]
}

print contact[222]  #打印字典的key为222的value
contact[222][2] = 12314  #将该key的第二个value改为12314
print contact[222]  #打印字典的key为222的value

执行结果
C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
[dfas, fdas, hjgkj]
[dfas, fdas, 12314]


contact = {                      
    222 : [alex,it,num], 
    3333 : [dsfa,dsfa],   
    324234 : [dsaf,fdasfsa]
}
字典的内置函数
>>> contact = {                      
...     222 : [alex,it,num], 
...     3333 : [dsfa,dsfa],   
...     324234 : [dsaf,fdasfsa]
... }
>>> import tab
>>> contact.
contact.clear(
contact.copy(
contact.fromkeys(
contact.get(
contact.has_key(
contact.items(
contact.iteritems(
contact.iterkeys(
contact.itervalues(
contact.keys(
contact.pop(
contact.popitem(
contact.setdefault(
contact.update(
contact.values(
contact.viewitems(
contact.viewkeys(
contact.viewvalues(
字典练习一
技术分享
2版本python 查看字典有没有这个key
>>> contact[4343]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4343
>>> contact.has_key(343)
False
>>> contact.has_key(3333)
True
清空字典contact.clear()
>>> contact.clear()

字典做列表contact.items()
>>> contact.items()
[(3333, [dsfa, dsfa]), (222, [alex, it, num]), (324234, [dsaf, fdasfsa])]
实验操作 一个参数只打印key
contact = {
    222 : [alex,it,num],
    3333 : [dsfa,dsfa],
    324234 : [dsaf,fdasfsa]
}

for i in contact:
    print  i,contact[i]
C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
3333 [dsfa, dsfa]
222 [alex, it, num]
324234 [dsaf, fdasfsa]

contact.items()  Key和value都打印
contact = {
    222 : [alex,it,num],
    3333 : [dsfa,dsfa],
    324234 : [dsaf,fdasfsa]
}
for k,v in contact.items():
print k,v
C:\Python27\python.exe //192.168.92.131/Share/py_training/seminar6/day2/dict.py
3333 [dsfa, dsfa]
222 [alex, it, num]
324234 [dsaf, fdasfsa]
注意
Contact.item()会把一个字典转换成列表,但是大数据的话,会花费一定时间的,那种情况下就会慢,特别大的数据不建议循环。如果非要在大数据循环用如下办法:
for i in contact:
    print  i,contact[i]
几万条数据没关系


字典增加、修改数据
a.get(key)  来确定这个key是否存在而不报错
>>> a = {name:alex,age:29}
>>> a[sex]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: sex
>>> b=a.get(sex)   #字典没有sex
>>> b
>>> print b    #查看为None
None
>>> b=a.get(name)
>>> b
alex
>>> print b
alex
> a.iteritems() 迭代器介绍 后面介绍
>>> a.iteritems()
<dictionary-itemiterator object at 0x7ff61e25b680>
>>> print 这是一个迭代器 加速搜索过程
这是一个迭代器 加速搜索过程
> a.keys()显示字典的key
>>> a.keys()
[age, name]
> a.values()显示字典value
>>> a.values()
[29, alex]
a.pop() 删除key
>>> a.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pop expected at least 1 arguments, got 0
>>> a.pop(age)
29
>>> a
{name: alex}
> a[age]=29   > a[sex]=Feale  增加更改字典的内容
>>> a[age]=29
>>> a[sex]=Male
>>> a
{age: 29, name: alex, sex: Male}
>>> a[sex]=Feale
>>> a
{age: 29, name: alex, sex: Feale}
字典是无序的

>>> a[birthday]=0624
>>> a
{age: 29, birthday: 404, name: alex, sex: Feale}
>>> a[country]=CN
>>> a
{country: CN, age: 29, birthday: 404, name: alex, sex: Feale}
>>> print 字典是无序的
字典是无序的
a.popitem()也是无序删除的
>>> a.popitem()
(country, CN)
>>> a.popitem()
(age, 29)
>>> a.popitem()
(birthday, 404)
注意 a.popitem()也是无序删除的

>a.setdefault保护字典的数据
>>> a.setdefault(Occupation)
>>> a
{name: alex, country: CN, sex: Feale, birthday: 404, Occupation: None}
>>> a.setdefault(Occupation,IT)
>>> a
{name: alex, country: CN, sex: Feale, birthday: 404, Occupation: None}
>>> a.setdefault(Height,170)
170
>>> a
{name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> a.setdefault(Height,190)
170
>>> a
{name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>>

聚合字典a.update()

>>> a.update()
>>> a
{name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> b={1:2,2:3,3:4}
>>> a.update(b)
>>> a
{1: 2, 2: 3, 3: 4, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> b={1:2,2:3,3:66}
>>> b
{1: 2, 2: 3, 3: 66}
>>> a.update(b)
>>> a
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> a.values()
[2, 3, 66, alex, CN, Feale, 404, 170, None]
>>> a.keys()
[1, 2, 3, name, country, sex, birthday, Height, Occupation]
>>> a.viewitems()
dict_items([(1, 2), (2, 3), (3, 66), (name, alex), (country, CN), (sex, Feale), (birthday, 404), (Height, 170), (Occupation, None)])
>>> a.viewkeys()
dict_keys([1, 2, 3, name, country, sex, birthday, Height, Occupation])
>>> v
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name v is not defined
>>> b
{1: 2, 2: 3, 3: 66}
清楚列表b.clear()

>>> b.clear()
>>> b
{}
>>> b[asdfa]=232
>>> b[sdf]=dfasf
>>> b
{asdfa: 232, sdf: dfasf}
>>> b
b            bool(        bytearray(
basestring(  break        bytes(
bin(         buffer(   
删除字典 del b   
>>> del b
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name b is not defined
>>> b = {}
>>> b[sdf]=dfasf
>>> b
{sdf: dfasf}
>>> b.copy()
{sdf: dfasf}
浅复制a.copy()  b字典 a字典一样,修改a ,b不变  
>>> b=a.copy()
>>> a
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> b
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> a[2]=T   ##改a字典的 key  2
>>> a
{1: 2, 2: T, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> b   #查看b  不变
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> c=b   #赋值字典的方法改一个都被改了
>>> c
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, Height: 170, Occupation: None}
>>> b[2]=fasdfa
>>> c
{1: 2, 2: 3, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, 2: fasdfa, Height: 170, Occupation: None}
>>> b[2]=123
>>> c
{1: 2, 2: 123, 3: 66, name: alex, country: CN, sex: Feale, birthday: 404, 2: fasdfa, Height: 170, Occupation: None}
>>>
字典练习二

九、set集合

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

技术分享
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
        """
        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
        """ 删除当前set中的所有包含在 new set 里的元素 """
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): # real signature unknown
        """ 移除元素 """
        """
        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
        """ 取交集,新创建一个set """
        """
        Return the intersection of two or more sets as a new set.
        
        (i.e. elements that are common to all of the sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ 取交集,修改原来set """
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ 如果没有交集,返回true  """
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): # real signature unknown
        """ 是否是子集 """
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs): # real signature unknown
        """ 是否是父集 """
        """ 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
        """ 差集,创建新对象"""
        """
        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
        """ 并集 """
        """
        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, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __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 __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 __iand__(self, y): # real signature unknown; restored from __doc__
        """ x.__iand__(y) <==> x&=y """
        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, y): # real signature unknown; restored from __doc__
        """ x.__ior__(y) <==> x|=y """
        pass

    def __isub__(self, y): # real signature unknown; restored from __doc__
        """ x.__isub__(y) <==> x-=y """
        pass

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

    def __ixor__(self, y): # real signature unknown; restored from __doc__
        """ x.__ixor__(y) <==> x^=y """
        pass

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

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

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

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass

    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

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

    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass

    def __rsub__(self, y): # real signature unknown; restored from __doc__
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, y): # real signature unknown; restored from __doc__
        """ x.__sub__(y) <==> x-y """
        pass

    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass

    __hash__ = None
set的官方文档

s = set()

a = {‘nick‘,‘jenny‘,‘suo‘}

#添加元素 
a = {‘nick‘,‘jenny‘,‘suo‘} 
a.add(‘The knife girl‘) 
print(a) 
  
#更新 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
a.update(b) 
print(a) 
  
  
#a中存在。b中不存在,赋给新值 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
set = a.difference(b) 
print(set) 
  
#a中存在。b中不存在,并更新a 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
a.difference_update(b) 
print(a) 
  
#交集,赋给新值 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
set = a.intersection(b) 
print(set) 
  
#交集,更新a 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
a.intersection_update(b) 
print(a) 
  
#对称交集 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
set = a.symmetric_difference(b) 
print(set) 
  
#对称交集,更新a 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
a.symmetric_difference_update(b) 
print(a) 
  
#并集,赋给新值 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
set = a.union(b) 
print(set) 
  
#如果没有交集,返回True,否则返回False 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘,‘The knife girl‘} 
set = a.isdisjoint(b) 
print(set) 
  
#是否是子序列 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘} 
set = a.issubset(b) 
print(set) 
  
#是否是父序列 
a = {‘nick‘,‘jenny‘,‘suo‘} 
b = {‘nick‘,‘jenny‘} 
set = a.issuperset(b) 
print(set) 
  
  
#移除指定元素,不存在不报错 
a = {‘nick‘,‘jenny‘,‘suo‘} 
a.discard(‘suo‘) 
print(a) 
  
#移除指定元素,不存在则报错 
a = {‘nick‘,‘jenny‘,‘suo‘} 
a.remove(‘suo‘) 
print(a) 
a.remove(‘suo‘) 
print(a) 
  
#移除随机元素,并赋给新值 
a = {‘nick‘,‘jenny‘,‘suo‘} 
set = a.pop() 
print(set) 
  
#清空 
a = {‘nick‘,‘jenny‘,‘suo‘} 
a.clear() 
print(a) 

十、for循环

循环可以迭代的对象里面的内容:

name = (‘nick‘,‘jenney‘) 
for i in name: 
    print(i) 

十一、enumrate创建序列号

 为一个可迭代的对象添加序号,可迭代的对象你可以理解成能用for循环的就是可迭代的。默认是编号是从0开始,可以设置从1开始

li = ["手机", "电脑", ‘鼠标垫‘, ‘游艇‘] 
for k, i in enumerate(li,1): 
    print(k,i) 
1 手机 
2 电脑 
3 鼠标垫 
4 游艇 

十二、range和xrange

迭代循环

  不会先在内存中创建,而是每次循环就创建一次,(节约内存)

for i in range(10):     #循环输出所生成的 0-9 
    print(i)  
  
for i in range(1,10,2): #输出所生成的 1 3 5 7 9 
    print(i) 

Attention最后要上硬菜啦

1、元素分类

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

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
list_a=[11,22,33,44,55,66,77,88,99,111]
dic = { "k1":[],"k2":[]}
for i in list_a:
    if i <= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)

print("小于66的值:%s 大于66的值:%s " % (dic["k1"],dic["k2"]))

2、查找

查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {‘k1‘: "alex", ‘k2‘: ‘ aric‘,  "k3": "Alex", "k4": "Tony"}
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
li = ["alec", " aric", "Alec", "Tony", "rain"]
tu = ("adnc", " arlc", "Amx", "Tony", "rain")
dic = {‘k1‘: "arm", ‘k2‘: ‘ apec‘,  "k3": "Alc", "k4": "Tony"}

a=[]
b=[]
c=[]
for i in li:
    key_a=i.strip()
    if (key_a.startswith("a") or key_a.startswith("A")) and key_a.endswith("c"):
        a.append(key_a)
for tup in tu:
    key_b = tup.strip()
    if (key_b.startswith("a") or key_b.startswith("A")) and key_b.endswith("c"):
        b.append(key_b)
for key in dic.keys():
    key_c = dic[key].strip()
    if (key_c.startswith("a") or key_c.startswith("A")) and key_c.endswith("c"):
        c.append(key_c)

print("列表内的符合元素为:",a)
print("元组内的符合元素为:",b)
print("字典内内的符合元素为:",c)

3、输出商品列表,用户输入序号,显示用户选中的商品  利用 enumrate

    商品 li = ["手机", "电脑", ‘鼠标垫‘, ‘游艇‘]
#方法一 
l1=[1,2,3,4] 
l2=["手机", "电脑", ‘鼠标垫‘, ‘游艇‘] 
d=dict(zip(l1,l2)) 
print(d) 
num=input("请输入商品编号:") 
print("你选择的商品为 %s" %d[int(num)]) 
  
#方法二 
li = ["手机", "电脑", ‘鼠标垫‘, ‘游艇‘] 
for k, i in enumerate(li): 
    print(k,i) 
k=input("请输入商品编号:") 
print("你选择的商品为 %s" % li[int(k)]) 

4、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
while True:
    salary = input("\033[33;1m请输入你的工资:\033[0m").strip()
    if len(salary) == 0:
        print("\033[31;1m工资不能为空重新输入~~\033[0m")
        continue
    elif salary.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue
    else:
        break
salary = int(salary)
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
def list_goods():
    print("\033[32;1m欢迎来到商城 ,商品列表:\033[0m")
    n = 1
    for i in goods:
        print(n, i["name"], i["price"])
        n += 1
list_goods()
shop_list = []
while True:
    chose = input("\033[33;1m输入选中的商品 输入 quit 离开:\033[0m").strip()
    if len(chose) == 0:
        print("\033[31;1m选择不能为空重新输入~~\033[0m")
        continue
    elif chose == ‘quit‘:
        while True:
            print("\033[34;1m购物车列表,如果要移除请选择序列号\033[0m")
            for x in enumerate(shop_list, 1):
                print(x[0], x[1])
            del_list = input("\033[33;1m你可以移除商品,输入你的购物车商品编号, 输入 quit 离开:\033[0m")
            if len(del_list) == 0:
                print("\033[31;1m不能为空~~\033[0m")
                continue
            elif del_list == ‘quit‘:
                break
            elif del_list.isdigit() != True:
                print("\033[31;1m必须是个数字\033[0m")
                continue
            elif int(del_list) > len(shop_list):
                print("\033[31;1m物品不存在\033[0m")
                continue
            del_list = int(del_list)
            for i in goods:
                if shop_list[del_list - 1] == i["name"]:
                    salary += i["price"]
                    print(
                        "\033[35;1m移除了商品:%s 返回现金:%s 元,目前余额:%s 元\033[0m" % (shop_list[del_list - 1], i["price"], salary))
            del shop_list[del_list - 1]
        break
    elif chose.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue

    chose = int(chose)
    if chose > len(goods):
        print("\033[31;1m你选择的商品不存在!!\033[0m")
        continue
    if goods[chose - 1]["price"] <= salary:
        salary -= goods[chose - 1]["price"]
        shop_list.append(goods[chose - 1]["name"])
        print("\033[35;1m你选择了:%s 还剩下工资:%s 你的购物车内有:%s\033[0m" % (goods[chose - 1]["name"], salary, shop_list))
        continue
    else:
        print("\033[31;1m余额不够\033[0m")
        ans = input("你是否想充值?yes=充值 no=返回商城列表:")
        if ans == ‘yes‘:
            while True:
                add_salary = input("输入你的充值额数:").strip()
                if len(add_salary) == 0:
                    add_salary = 0
                    break
                elif add_salary.isdigit() != True:
                    print("\033[31;1m输入必须是数字~~~")
                    continue
                else:
                    break
            add_salary = int(add_salary)
            
            salary += add_salary
            print("充值金额:%s 现在工资:%s 元 " % (add_salary, salary))
        elif ans == ‘no‘:
            list_goods()
            continue
balance = salary
if len(shop_list) < 1:
    shop_list = "0件"
print(购买的商品: %s 余额是:%s" % (shop_list, balance))

 

5、用户交互,显示省市县三级联动的选择

 dic = { 
    "河北": { 
        "石家庄": ["鹿泉", "藁城", "元氏"], 
        "邯郸": ["永年", "涉县", "磁县"], 
    }, 
    "湖南": { 
        "长沙":[‘a‘,‘b‘,‘c‘], 
        "株洲":[‘d‘,‘e‘,‘f‘] 
    }, 
    "湖北": { 
        "武汉":[‘g‘,‘h‘,‘i‘], 
        "黄石":[‘j‘,‘k‘,‘l‘] 
    } 
} 
 
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
chinamap = {
    "山东省":{
        "济南":["市中区","历下区","天桥区","槐荫区","历城区","长清区","章丘市","平阴县","济阳县","商河县","其他"],
        "青岛":["市南区","市北区","城阳区","四方区","李沧区","黄岛区","崂山区","胶南市","胶州市","平度市","莱西市","即墨市","其他"]
    },
    "北京市":{
        "北京":["东城区","西城区","崇文区","宣武区","朝阳区","海淀区","丰台区","石景山区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","门头沟区","密云县","延庆县","其他"],
    },
    "广东省":{
        "广州":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市","其他"],
        "深圳":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区","其他"]
    },
    "河北省":{
        "邯郸":[
            "成安县","磁县","大名县","肥乡县","馆陶县","广平县","邯郸市","邯郸县","鸡泽县","临漳县","邱县","曲周县","涉县","魏县","武安市","永年县"
        ],
        "衡水":[
            "安平县","阜城县","故城县","衡水市","冀州市","景县","饶阳县","深州市","武强县","武邑县","枣强县"
        ],
        "石家庄":[
            "高邑县","晋州市","井陉县","灵寿县","鹿泉市","平山县","深泽县","石家庄市","无极县","辛集市","新乐市","行唐县","元氏县","赞皇县","赵县","正定县","藁城市","栾城县"
        ]
    }
}
chose=[]
def zero():
    print("\033[31;1m选择不能为空,清重新输入~~\033[0m")
def crre():
    print("\033[31;1m你的选择不正确,清重新输入~~\033[0m")

print("\033[32;1m省列表如下:\033[0m\033[0m")
for key in chinamap.keys():
    print(key)
while True:
    sheng=input("\033[33;1m请输入省,quit for leave:\033[0m").strip()
    if len(sheng) == 0:
        zero()
        continue
    elif sheng == ‘quit‘:
        break
    elif sheng not in chinamap.keys():
        crre()
        continue

    else:
        chose.append(sheng)
        print("\033[32;1m市列表如下:\033[0m")
        for key_shi in chinamap[sheng].keys():
            print(key_shi)
        while True:
            shi=input("\033[33;1m请输入市:quit for leave:\033[0m").strip()
            if len(shi) == 0:
                zero()
            elif shi == ‘quit‘:
                print("\033[35;1m你选择的省:%s \033[0m"%(chose[0]))
                exit()
            elif shi not in chinamap[sheng].keys():
                crre()
            else:
                chose.append(shi)
                print("\033[32;1m县区列表如下:\033[0m")
                for key_xian in enumerate(chinamap[sheng][shi],1):
                    print(key_xian[0],key_xian[1])
                while True:
                    xian=input("\033[33;1m请输入县序号,quti for leave:\033[0m").strip()
                    if len(xian) == 0:
                        zero()
                    elif xian == ‘quit‘:
                        print("\033[35;1m你选择的省:%s 市是:%s \033[0m"%(chose[0],chose[1]))
                        exit()
                    elif xian.isdigit() != True:

                        print("\033[31;1m必须是 数字\033[0m")
                        continue
                    elif int(xian) > len(chinamap[sheng][shi]):
                        print("\033[31;1m选择不存在\033[0m")
                        continue
                    else:
                        xian=int(xian)
                        chose.append(chinamap[sheng][shi][xian-1])
                        break
                break
        break
if len(chose) < 1:
    print("\033[35;1m你什么也没选~~!!\033[0m")
else:
    print("\033[35;1m你选择的省:%s 市是:%s 县是:%s\033[0m"%(chose[0],chose[1],chose[2]))

Python全栈之路---运算符与基本的数据结构

标签:

原文地址:http://www.cnblogs.com/mosson/p/5624125.html

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