Python 数据类型

进制

  • 二进制,01
  • 八进制,01234567
  • 十进制,0123456789
  • 十六进制,012345678910ABCDEF

整数

如:18,37,84

每一个整数都具备如下功能:

In [ ]:
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

浮点型

如:3.14,2.88

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

In [ ]:
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

float

算数运算

数学运算

In [1]:
a = 10
b = 20

a + b
a - b
a * b
b / a
b % a
a ** b
9 // 2
9.0 // 2.0
Out[1]:
30
Out[1]:
-10
Out[1]:
200
Out[1]:
2.0
Out[1]:
0
Out[1]:
100000000000000000000
Out[1]:
4
Out[1]:
4.0

字符串

一个有序的字符的集合,用来存储和表现文本的信息。

字符串表达形式:

In [2]:
# 空字符串
s = ''
s
s = ""
s
Out[2]:
''
Out[2]:
''
In [3]:
# 字符串中包含引号
s1 = "what's you name?"
s2 = 'my name is "liangxiansen"'

print(s1, s2, sep='\n')
what's you name?
my name is "liangxiansen"
In [4]:
# 三重引号字符串块

s3 = """
Infomation of user liangxiansen:
-------------------
Name:   liangxiansen
Age :   12
Job :   Programmer
---------End-------
"""

print(s3)
Infomation of user liangxiansen:
-------------------
Name:   liangxiansen
Age :   12
Job :   Programmer
---------End-------

In [5]:
# Raw字符串,可以对字符串中的特殊字符转义
s4 = r'liangxiansen \n'
s4
Out[5]:
'liangxiansen \\n'
In [6]:
# Unicode 字符串
s5 = u'liangxiansen'
s5
Out[6]:
'liangxiansen'
In [7]:
# 字节字符串
s6 = b'liangxiansen'
s6
Out[7]:
b'liangxiansen'

字符串操作:

每个字符串都支持下面操作:

In [ ]:
class str(basestring):
    """
    str(object='') -> string
    
    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    """
    def capitalize(self):  
        """ 首字母变大写 """
        """
        S.capitalize() -> string
        
        Return a copy of the string S with only its first character
        capitalized.
        """
        return ""

    def center(self, width, fillchar=None):  
        """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
        """
        S.center(width[, fillchar]) -> string
        
        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):  
        """ 子序列个数 """
        """
        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 decode(self, encoding=None, errors=None):  
        """ 解码 """
        """
        S.decode([encoding[,errors]]) -> object
        
        Decodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    def encode(self, encoding=None, errors=None):  
        """ 编码,针对unicode """
        """
        S.encode([encoding[,errors]]) -> object
        
        Encodes S using the codec registered for encoding. encoding defaults
        to the default encoding. 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 is able to handle UnicodeEncodeErrors.
        """
        return object()

    def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 结束 """
        """
        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=None):  
        """ 将tab转换成空格,默认一个tab转换成8个空格 """
        """
        S.expandtabs([tabsize]) -> string
        
        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):  
        """ 寻找子序列位置,如果没找到,则异常 """
        """
        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.format(*args, **kwargs) -> string
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def index(self, sub, start=None, end=None):  
        """ 子序列位置,如果没找到,则返回-1  """
        S.index(sub [,start [,end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和数字 """
        """
        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):  
        """ 是否是字母 """
        """
        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 isdigit(self):  
        """ 是否是数字 """
        """
        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 islower(self):  
        """ 是否小写 """
        """
        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 isspace(self):  
        """
        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):  
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        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):  
        """ 连接 """
        """
        S.join(iterable) -> string
        
        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):  
        """ 内容左对齐右侧填充 """
        """
        S.ljust(width[, fillchar]) -> string
        
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 变小写 """
        """
        S.lower() -> string
        
        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左侧空白 """
        """
        S.lstrip([chars]) -> string or unicode
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割后三部分 """
        """
        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):  
        """ 替换 """
        """
        S.replace(old, new[, count]) -> string
        
        Return a copy of string 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):  
        """
        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):  
        """
        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):  
        """
        S.rjust(width[, fillchar]) -> string
        
        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):  
        """
        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=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string 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 or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割 maxsplit最多分割几次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string 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=False):  
        """ 根据换行分割 """
        """
        S.splitlines(keepends=False) -> 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):  
        """ 是否起始 """
        """
        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):  
        """ 移除两段空白 """
        """
        S.strip([chars]) -> string or unicode
        
        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.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大写变小写小写变大写 """
        """
        S.swapcase() -> string
        
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string
        
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

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

        """
        S.translate(table [,deletechars]) -> string
        
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string
        
        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定长度的字符串原字符串右对齐前面填充0"""
        """
        S.zfill(width) -> string
        
        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 _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
        pass

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

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

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

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

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

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

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

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

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        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, string=''): # known special case of str.__init__
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

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

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

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

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        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 __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

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

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

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

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

str
In [8]:
# 字符串拼接
LastName = 'Liang'
FirstName = 'Kevin'

MyName = FirstName + ' ' + LastName
print(MyName)
Kevin Liang
In [9]:
# 字符串重复
print('liang' * 3)
liangliangliang
In [10]:
# 字符串长度
len('liang')
Out[10]:
5

字符串索引,分片的使用:

之前提到过,字符串是字符的一个有序集合,我们可以操作这个集合。

通过 str[index] 来获取这个字符串中具体某个位置的字符:

In [11]:
str1 = 'liang'
str1[0]
str1[1]
str1[2]
str1[3]
str1[4]
Out[11]:
'l'
Out[11]:
'i'
Out[11]:
'a'
Out[11]:
'n'
Out[11]:
'g'

上面例子中 [ ] 中括号里面的数字被称为 索引 ,字符串中第一个字符的 索引0, 然后依次递增。

字符串也可以取出一定范围内的字符,叫 分片

通过 str[star_index: end_index] 来获取起始索引 ~ 结束索引范围中的字符,但是注意不包含结束索引位的字符。

例如,你要取 0,1,2, 你要取这三个索引位置的字符,从起始索引0 到 索引2 的都取出来,但是取的时候不包含结束索引的字符,所以需要注意你想要取的结束索引的位置 +1 ,取开始的索引位到这个位置之前的所有字符。

In [12]:
str1[0:3]
Out[12]:
'lia'
In [13]:
# 取中间到最后
str2 = 'liangxiang'
length = len(str2)
mid = length // 2
print(str2[mid:])
xiang

我缺省了结束索引就会默认取从起始索引到最后一个索引所有的字符。

也可以缺省起始索引:

In [14]:
# 取从开头到中间
print(str2[:mid])
liang

起始索引和结束索引使用负数,即反转分片,从序列的最后往前取值。

In [15]:
str2[-9:-2]
Out[15]:
'iangxia'

str[起始索引:结束索引:步长]

这里新增了 步长 这个概念,在默认情况下,步长为1,即从左至右一个一个取。设置步长可以实现每多少个取一个。看下面的例子,设置步长为2,即每2个取一个,另外一个则跳过不取。

In [16]:
# 隔一个字符选取
print(str2)
print(str2[::2])
liangxiang
lagin

步长还可以设置为负数,设置为负数则会反转整个序列:

In [17]:
str2[::-1]
Out[17]:
'gnaixgnail'
In [18]:
str2[2:5]
str2[4:1:-1]
str2[4::-1]
Out[18]:
'ang'
Out[18]:
'gna'
Out[18]:
'gnail'

因为设置了负数步长,整个序列进行了反转。索引取值也要从反过来从大到小取值,例如反转后取分片[4:1]的值,相对应的是正序[2:5]值。 因为反序后的序列取值会包含起始索引和结束索引,

需要注意的是,反转序列很常用,但是反转序列分片不太符合人类常用数学习惯,不建议使用,原因是难以理解,阅读不友好,使用正序分片后再做反转会好很多。

字符串常用方法:

In [19]:
# 字符串strip方法去除字符串两端的空格
"   liangxiansen   ".strip()
"   liangxiansen   ".lstrip() # 去掉字符串左边的空格
"   liangxiansen   ".rstrip() # 去掉字符串右边的空格
Out[19]:
'liangxiansen'
Out[19]:
'liangxiansen   '
Out[19]:
'   liangxiansen'
In [20]:
# 字符串split方法分隔字符串返回list
"  Kevin liang  ".split() # 默认参数为空格,以空格分割字符串。
"liang#xian#sen".split('#')  # 也可以传一个字符,通过这个字符分割字符串
Out[20]:
['Kevin', 'liang']
Out[20]:
['liang', 'xian', 'sen']
In [21]:
# 字符串join方法来对字符串进行拼接
name_list = " Kevin Liang ".split()   # 分隔字符串
new_name = "/".join(name_list)  # 拼接字符串
print(new_name)
Kevin/Liang
In [22]:
# 字符串find方法得到字符在字符串中得索引
name = "Kevin Liang"
name.find('v')
Out[22]:
2
In [23]:
# 字符串replace方法字符串替换
name.replace('iang', 'ing') # 需要注意的是,replace 并不是在原字符串上修改,而是基于原字符串返回一个修改后的新字符串
Out[23]:
'Kevin Ling'
In [24]:
# 字符串center方法来对字符串居中
name.center(30, '=') # 第一个参数设置字符串宽度,第二个参数设置填充空白的字符串,不传默认为空格
Out[24]:
'=========Kevin Liang=========='
In [25]:
print("是否‘K‘开头:\t", name.startswith('K')) # 判断什么字符开头
print("是否‘g’结尾:\t", name.endswith('g'))   # 判断什么字符结尾
print("没有特殊字符:\t", name.isalnum())      # 是否全是字母和数字,并至少有一个字符
print("是否全是字母:\t", name.isalpha())      # 是否全是字母,并至少有一个字符
print("是否全是数字:\t", name.isdigit())      # 是否全是数字,并至少有一个字符
print("是否全空白字符:\t", name.isspace())    # 是否全是空白字符,并至少有一个字符
print("是否全是小写:\t", name.islower())     # 中的字母是否全是小写
print("是否全是大写:\t", name.isupper())     # 中的字母是否便是大写
print("是否首字母大写:\t", name.istitle())   # 是否是首字母大写的
是否‘K‘开头:	 True
是否‘g’结尾:	 True
没有特殊字符:	 False
是否全是字母:	 False
是否全是数字:	 False
是否全空白字符:	 False
是否全是小写:	 False
是否全是大写:	 False
是否首字母大写:	 True
In [26]:
print(name)
name.swapcase()   # 大小写互换
name.title()      # 单词首字母大写
name.capitalize() # 字符串首字母大写,其余字符小写
name.upper()      # 全部字符转变为大写
name.lower()      # 全部字符转变为小写
Kevin Liang
Out[26]:
'kEVIN lIANG'
Out[26]:
'Kevin Liang'
Out[26]:
'Kevin liang'
Out[26]:
'KEVIN LIANG'
Out[26]:
'kevin liang'

元组

元组是一个不可更改得有序得序列,支持任意类型得,任意嵌套数据

元组得输写格式:用小括号包裹元素:(1,2,3,"liang")

In [27]:
# 创建元组
t = (1, 2, 3, 'liang')
type(t)
Out[27]:
tuple

接下来说一个大家都知道的一个关于元组使用的问题:

In [28]:
t1 = (1)
type(t1)
Out[28]:
int

从之前我们知道元组的定义就是两个括号包裹住,就是元组,但是上面的例子查看类型却不是元组。

只有一个元素,这样的写法Python解释器不认为这是一个元组,如果只有一个元素,正确的写写法应该是:

In [29]:
t2 = (1,)
type(t2)
Out[29]:
tuple

需要在元素后面加一个逗号 “,” 让解释器知道你这是一个元组,当然还有调用 Python 的 tuple 函数来创建元组对象。

In [30]:
t3 = tuple()
t4 = tuple('liang')
type(t3)
type(t4)

t3
t4
Out[30]:
tuple
Out[30]:
tuple
Out[30]:
()
Out[30]:
('l', 'i', 'a', 'n', 'g')

通过tuple 可以创建空元组,也可以将另一个序列变成元组。

元组的分片和前面说的大字符串分片一摸一样:

In [31]:
# 元组嵌套
tp = (1, 2, 3, 4, 5, 6, 7, 8, 9, (1, 2, 3),)
print(tp[0])      # []中输入索引进行分片,索引起始位为0
print(tp[3:6])    # 显示4~6得元素
print(tp[3:])     # 显示4到最后
print(tp[:6])     # 显示从开头到7的元素
print(tp[-1])     # 显示倒数第一个
print(tp[-4:-2])  # 显示倒数第4个到倒数第二个,(范围切片,结束位不包括在内,即"到什么什么之前")
print(tp[:])      # 显示全部
print(tp[::2])    # 按照步长为2,显示全部,步长即两个元素之间索引闲差多少执行一次
print(tp[9][0])   # 嵌套分片
1
(4, 5, 6)
(4, 5, 6, 7, 8, 9, (1, 2, 3))
(1, 2, 3, 4, 5, 6)
(1, 2, 3)
(7, 8)
(1, 2, 3, 4, 5, 6, 7, 8, 9, (1, 2, 3))
(1, 3, 5, 7, 9)
1
In [32]:
# index方法查找元素相对应得索引
tp.index(9)
Out[32]:
8
In [33]:
# count查看元素在元组中得数量
tp.count(3) 
Out[33]:
1

你可能疑惑,加上后面嵌套的元组里面也有一个3,应该是2个3啊; 是的,是找不出来的。 序列里面嵌套序列,对外围序列来说,里面嵌套的序列对他来说是一个对象,它是不管这个对象里面有什么的。

列表

List 是Python 中最灵活的有序的集合,列表可以包含任何类型的对象:数字、字符串、甚至其他列表。支持在原处修改(可修改的),也可以进行分片操作

List书写格式用 [ ] 包裹起来,元素与元素之间用 "," 逗号分隔:

In [34]:
l = []
type(l)
Out[34]:
list

list 函数还可以将其他序列转换成列表:

In [35]:
list('liang')
list((1, 2, 3, 4, ))
Out[35]:
['l', 'i', 'a', 'n', 'g']
Out[35]:
[1, 2, 3, 4]

列表分片:

其他序列的分片操作是在原有数据上筛选出想要的数据,并不会修改原数据内容;

但是由于list是一个灵活可修改的有序序列,list是可以修改原数据的。

In [36]:
# 创建了换一个List, 而且里面还嵌套了List
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]

list1[0]
list1[1]
list1[3:6]
list1[3:]
list1[:6]
list1[-1][0]
list1[-9:-4]
list1[::-1]
list1[::2]
Out[36]:
1
Out[36]:
2
Out[36]:
[4, 5, 6]
Out[36]:
[4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]
Out[36]:
[1, 2, 3, 4, 5, 6]
Out[36]:
10
Out[36]:
[2, 3, 4, 5, 6]
Out[36]:
[[10, 11, 22, 33, 44], 9, 8, 7, 6, 5, 4, 3, 2, 1]
Out[36]:
[1, 3, 5, 7, 9]

通过分片取出对应索引为止的 Value, 然后通过对这个索引位置重新赋值,就会修改原list中该索引位置的值:

In [37]:
list1[0] = 111
print(list1)
[111, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]
In [38]:
# 列表append方法对列表中添加元素

list2 = ['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']
list2.append('Liangxiansen')
print(list2)
['Kevin', 'Lina', 'Eric', 'Alex', 'Lina', 'Liangxiansen']
In [39]:
# 列表count方法查看指定元素在列表中的数量
list2.count('Lina')
Out[39]:
2
In [40]:
# 列表pop方法删除列表中的最后一个元素
print(list2)
list2.pop()
print(list2)
['Kevin', 'Lina', 'Eric', 'Alex', 'Lina', 'Liangxiansen']
Out[40]:
'Liangxiansen'
['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']
In [41]:
# 列表remove方法删除列表指定元素,执行一次只会删除一个,默认是删除找到的第一个。
print(list2)
list2.remove('Lina')
print(list2)
['Kevin', 'Lina', 'Eric', 'Alex', 'Lina']
['Kevin', 'Eric', 'Alex', 'Lina']
In [42]:
# 列表index方法获取指定的元素的索引
list2.index('Alex')
Out[42]:
2
In [43]:
# 列表extend方法拼接列表
list2.extend(list1)
print(list2)
['Kevin', 'Eric', 'Alex', 'Lina', 111, 2, 3, 4, 5, 6, 7, 8, 9, [10, 11, 22, 33, 44]]
In [44]:
list2.sort()
print(list2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-c0dd03032db6> in <module>()
----> 1 list2.sort()
      2 print(list2)

TypeError: unorderable types: int() < str()
In [45]:
list1.sort()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-05e4223c8627> in <module>()
----> 1 list1.sort()

TypeError: unorderable types: list() < int()

上面两个报错是在使用列表sort()方法的时候,里面的元素要统一类型,不要有对象。

In [46]:
list3 = [7, 3, 2, 6, 9, 0, 5, 1, 4, 8]
list3.sort()
print(list3)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [47]:
# 列表reverse方法对列表进行反转
list3 = [7, 3, 2, 6, 9, 0, 5, 1, 4, 8]
list3[::-1]
list3.reverse()
print(list3)
Out[47]:
[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]
[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]

List 的reverse方法只会根据索引粗暴的反转 List, 并不会做排序,和分片 [::-1] 效果一样

In [48]:
# 列表insert方法在列表的指定位置插入新值。
print(list3)
list3.insert(2, '66') # 接收两个参数,第一个是索引,第二个是值,
print(list3)
[8, 4, 1, 5, 0, 9, 6, 2, 3, 7]
[8, 4, '66', 1, 5, 0, 9, 6, 2, 3, 7]
In [49]:
# 列表clear方法清空列表
list3.clear()
print(list3)
[]

下面我写了一个处理多层嵌套List 的一个例子,看下结果就行了,这里不用学习。

In [53]:
# 使用递归遍历多层嵌套List,把所有的9替换成9999
that_list = [1, 5, [9, 4, 3, 5, [9, 8, [88, 9, 2], 3, 5], 2, 6], 9, [3, 6, 9, [9, 2], 3], 8]  # 创建多层嵌套list

# 创建递归函数
def change_all(ll):
    for i in ll:
        if i == 9:
            key = ll.index(i)
            ll[key] = 9999
        elif isinstance(i, list):  # 如果该对象是list的实例
            change_all(i)  # 再次调用自己


change_all(that_list)
print(that_list)
[1, 5, [9999, 4, 3, 5, [9999, 8, [88, 9999, 2], 3, 5], 2, 6], 9999, [3, 6, 9999, [9999, 2], 3], 8]

字典

列表允许你通过一个变量存储大量的信息,但试想以下场景,用列表实现就可能 效率较低了:

  1. 存储的信息量越来越多,有的时候找一个数据可能要循环整个列表,耗时较长。

  2. 单个元素包含的信息量变多时,比如,之前只是存储姓名列表,现在是要存 储姓名、年龄、身份证号、地址、工作等这个人的很多信息,用列表去存储 很费劲

  3. 要求存储的数据是不重复,我们知道列表是允许的重复值的,当然想存储时 就让我的数据默认就是唯一的话,用列表就不可以了

以上这些是列表不擅长的地方,却恰恰是接下来要讲的 dict 所擅长的方面, dict 使用 key-value 的形式存储数据, dict 的 key 是唯一的,所以你可以通过 key 来唯一的定位到你的数据。之所以叫字典(在其它语言中称为 map),是因为 dict 的数据结构跟我们生活中用的字典是一样的,查英文字典时,输入单词,就可以 定位到这个单词意思的详细解释,其中这个单词就是 key,对应的词义解释就是 value.

字典有如下特点:

  1. key-value 格式,key 是唯一的

  2. 无序,与列表有序的特点不同,字典是无序的,列表之所以有序是因为你需要通过索引来定位相应元素,而字典已经可以通过 key 来定位相应 value,因 此为了避免浪费存储空间,字典不会对数据的位置进行纪录,当然如果你想 让其变成有序的,也是有方法的,这个我们以后再讲。

  3. 查询速度很快, dict是基于hash表的原理实现的, 是根据关键字(Key/value) 而直接访问在内存存储位置的数据结构。也就是说,它通过把键值通过一个 函数的计算,映射到表中一个位置来访问记录,这加快了查找速度。这个映 射函数称做散列函数,存放记录的数组称做散列表。由于通过一个 key 的索 引表就直接定位到了内存地址,所以查询一个只有 100 条数据的字典和一个 100 万条数据的字典的速度是查不多的。

In [54]:
# 创建字典, Key/Value 格式

user_profiles = {
    "name": "Kevin",
    "age": 12,
    "job": "IT"
}
print(user_profiles)
print(user_profiles['name'])
print(user_profiles['age'])
print(user_profiles['job'])
{'age': 12, 'job': 'IT', 'name': 'Kevin'}
Kevin
12
IT

字典(dict) 由一对花括号 { } 包含,里面的每一组 Key:value 数据,以逗号分隔, Key 必须是字符串。

每一个 Dict 对象都包含以下方法:

In [ ]:
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
In [55]:
# 使用key,修改value
user_profiles['name'] = 'Liangxiansen'  # 修改name对应的value,如果name不存在就会创建一个这样得对应值
print(user_profiles)
{'age': 12, 'job': 'IT', 'name': 'Liangxiansen'}
In [56]:
# 字典的pop方法删除指定一条数据
user_profiles.pop('name')  # 删除'name'这条数据
print(user_profiles)
Out[56]:
'Liangxiansen'
{'age': 12, 'job': 'IT'}
In [57]:
# 字典的popitem方法会随机删除一条字典得数据(尽量不要使用)
user_profiles.popitem()  # 随机删除一条数据,dict为空得时候会报错
print(user_profiles)
Out[57]:
('age', 12)
{'job': 'IT'}
In [58]:
# 字典的items方法可以将字典的key,value以字典视图的形式返回(尽量不要使用,大字典的时候,你没发确认有多大数据)
user_info = {
    "name": "lianglian",
    "age": 12,
    "job": "IT"
}

new_user_info = list(user_info.items())  # 将dict的key,value转换成列表字典视图形式的list,再通过list函数转换成真正可操作的list
print(new_user_info)
[('age', 12), ('job', 'IT'), ('name', 'lianglian')]
In [117]:
# 字典的values方法可以将字典的value以字典视图形式返回(大字典得时候,谨慎使用,你没法确认下面嵌套字典有多大数据)
new_user_info = list(user_info.values())  # 将dict的key,value转换成字典视图形式的list,再通过list函数转换成真正可操作的list
print(new_user_info)
['lianglian', 'IT', 12]
In [59]:
# 字典的keys方法可以将字典的key以字典视图的形式返回(相对上面两种推荐使用这种,通过key去取value)
print(user_info.keys())  # 将dict的key转换成字典视图形式的list,再通过list函数转换成真正可操作的list
print(list(user_info.keys())) # 使用list函数变成列表。
dict_keys(['age', 'job', 'name'])
['age', 'job', 'name']
In [60]:
# 字典的get方法安全的去查询一个key得value,不存在得key不会报错

print(user_info.get('na'))  # 查找一个key,如果存在则返回value,如果不存在不会报错,返回None
print(user_info.get('name'))
None
lianglian
In [61]:
# 字典的setdefault方法可以安全得去修改一个key得值,这个key存在不会覆盖掉

print(user_info.setdefault('name','Test'))
print(user_info)
# 找一个key为'name'的记录,如果这个key不存在,那就创建一个叫'name'的key,
# 并且将其value设置为'Test',如果这个key存在,就直接返回这个key的value
lianglian
{'age': 12, 'job': 'IT', 'name': 'lianglian'}
In [62]:
# 通过字典的update方法拿一个新的字典去更新一个旧的字典

test_dict = {
    'age': 18,
    'name': 'liang',
    'address': 'BeiJing'
}

user_info.update(test_dict) 
print(user_info)
{'age': 18, 'job': 'IT', 'address': 'BeiJing', 'name': 'liang'}
In [63]:
# 字典的clear方法清除字典全部内容,保留字典类型

test_dict.clear()  # 清空dict
print(test_dict)
{}
In [64]:
# 字典的copy方法copy属于浅copy
profiles_info = {
    "name": "lianglian",
    "age": 12,
    "job": "IT",
    "hobby": {
        "book": "三国演义",
        "movement": "skateboard" 
    }
}

new_profiles_info = profiles_info.copy()
print(profiles_info)
print(new_profiles_info)

profiles_info['age'] = 16
profiles_info['hobby']['book'] = '三体'
print(profiles_info)
print(new_profiles_info)
{'age': 12, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}, 'name': 'lianglian'}
{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}
{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}
{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}}

按理说我copy了一份profiles_info 到 new_profiles_info 它们应该是独立得两份数据,那么我修改profiles_info, new_profiles_info是不会改变的,这里在修改'age'得时候确实是这样,没有错,但是修改profiles_info嵌套得字典里面得内容得时候new_profiles_info里面的内容也变了,为什么呢? 看下面图:

lightcopy

deepcopy

In [65]:
# 字典的copy模块的deepcopy方法实现深copy
import copy
profiles_info = {
    "name": "lianglian",
    "age": 12,
    "job": "IT",
    "hobby": {
        "book": "三国演义",
        "movement": "skateboard" 
    }
}

new_profiles_info = copy.deepcopy(profiles_info)
print(profiles_info)
print(new_profiles_info)

profiles_info['age'] = 16
profiles_info['hobby']['book'] = '三体'
print(profiles_info)
print(new_profiles_info)
{'age': 12, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}, 'name': 'lianglian'}
{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}
{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}
{'age': 12, 'name': 'lianglian', 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三国演义'}}
In [66]:
# 遍历字典

print(profiles_info)

for key in profiles_info:
    value = profiles_info[key]
    print(key, value)
{'age': 16, 'job': 'IT', 'hobby': {'movement': 'skateboard', 'book': '三体'}, 'name': 'lianglian'}
age 16
job IT
hobby {'movement': 'skateboard', 'book': '三体'}
name lianglian

集合

python 的 集合(set) 和其他语言类似, 是一个无序 不重复 元素集, 基本功能包括关系测 适合消除重复元素. 集合对象还支持 union(联合), intersection(交), difference(差)sysmmetric difference(对称差集)等数学运算.

set 支持 x in set, len(set),和 for x in set。作为一个无序的集合,set 不记录元素位置或者插入点。因此,set 不支持 indexing, slicing, 或其它类序列 (sequence-like)的操作。

与列表和元组不同,集合是无序的,也无法通过数字进行索引。此外,集合中的元素 不能重复:

In [67]:
# 通过set关键字函数来创建集合
s = set('hello')
l = list('hello')
print(s)
print(l)
{'e', 'o', 'l', 'h'}
['h', 'e', 'l', 'l', 'o']

如上结果中少了一个"l",set是会默认去除重复的。

In [68]:
t = set('world')

s.union(t)    #  s 和 t 的并集(两个合并到一块)
print(s | t)

print(s.intersection(t))  # s 和 t的交集(取出两个都有的)
print(s & t)

print(s.difference(t))  # 求差集(项在s中,但是不在t中)
print(s - t) 

print(s.symmetric_difference(t)) # 对称差集(两个中不相同的)
print(s ^ t)  
Out[68]:
{'d', 'e', 'h', 'l', 'o', 'r', 'w'}
{'h', 'e', 'w', 'o', 'd', 'r', 'l'}
{'o', 'l'}
{'o', 'l'}
{'e', 'h'}
{'e', 'h'}
{'e', 'w', 'd', 'r', 'h'}
{'e', 'w', 'd', 'r', 'h'}
In [69]:
# 集合add方法添加新元素
s
s.add('u')
print(s)
Out[69]:
{'e', 'h', 'l', 'o'}
{'e', 'o', 'l', 'u', 'h'}
In [70]:
# 集合update方法添加多个元素,可以接受迭代的对象,循环add,批量添加
# add <-->update 的区别

t = set("Hello")
t.add("world") 
print(t)     

t1 = set("Hello")
t1.update("world")
print(t1)
{'world', 'e', 'o', 'H', 'l'}
{'H', 'e', 'w', 'o', 'd', 'r', 'l'}
In [71]:
# 差集更新(在s中有的,在t中没有更新到s)
s = set("Hello")
t = set("World")

print(s)
s.difference_update(t)
print(s)
{'e', 'o', 'H', 'l'}
{'H', 'e'}
In [72]:
# 集合remove方法,移除指定值,如果没有会报错
s = set("Hello")
s.remove("H")
print(s) 
{'e', 'o', 'l'}
In [73]:
# 集合discard方法,移除指定值,如果没有不会报错
s = set("Hello")
s.discard("h")
print(s)
{'e', 'o', 'H', 'l'}
In [74]:
old_dict = {
    "#1": 8,
    "#2": 4,
    "#4": 2,
}

new_dict = {
    "#1": 4,
    "#2": 4,
    "#3": 2,
}

# old_dict 中没有, new_dict 中有的加到 old_dict
old_set = set(old_dict.keys())
new_set = set(new_dict.keys())

remove_set = old_set.difference(new_set)
add_set = new_set.difference(old_set)
update_set = old_set.intersection(new_set)

print("删除:%s\n添加:%s\n更新%s\n" % (remove_set, add_set, update_set))
删除:{'#4'}
添加:{'#3'}
更新{'#2', '#1'}

运算

比较运算

比较运算

赋值运算

赋值运算

逻辑运算

逻辑运算

成员运算

成员运算

身份运算

身份运算

位运算

位运算

运算优先级

运算优先级

内存指针

值传递:我创建了两个变量,分别指向内存中对应的两个地址空间的值:

In [20]:
name1 = 'liangxiansen'
name2 = 'Kevin'

print(name1)
print(name2)

print('name1 内存地址:', id(name1))
print('name2 内存地址:', id(name2))
liangxiansen
Kevin
name1 内存地址: 4350694512
name2 内存地址: 4322625272

值传递

指针传递:我创建了一个变量,使用另一个变量赋值的内存指针赋值:

In [22]:
name3 = name1

print(name1)
print(name3)

print('name1 内存地址:', id(name1))
print('name3 内存地址:', id(name3))
liangxiansen
liangxiansen
name1 内存地址: 4350694512
name3 内存地址: 4350694512

地址传递