zoukankan      html  css  js  c++  java
  • python 学习之数据类型和for循环

    一 基本数据类型

    比如数字来说:

      数字的方法都放在int类中,而数字是类的实例化。 如上图所示

    1,整型

    复制代码
    n1=4
    n2=4
    print(n1.__add__(n2))
    
    a=18
    print("the num 18 's bit is:",a.bit_length())
    复制代码
     class int(object):
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        """
        def bit_length(self): # real signature unknown; restored from __doc__
            """ 计算给出数字的二进制最小位数
            int.bit_length() -> int
            
            Number of bits necessary to represent self in binary.
            >>> bin(37)
            '0b100101'
            >>> (37).bit_length()
            6
            """
            return 0
    
        def conjugate(self, *args, **kwargs): # real signature unknown
            """返回该复数的共轭复数"""
     """ Returns self, the complex conjugate of any int. """
        pass
    
    @classmethod # known case
    def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.from_bytes(bytes, byteorder, *, signed=False) -> int
        
        Return the integer represented by the given array of bytes.
        
        The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        pass
    
    def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        int.to_bytes(length, byteorder, *, signed=False) -> bytes
        
        Return an array of bytes representing an integer.
        
        The integer is represented using length bytes.  An OverflowError is
        raised if the integer is not representable with the given number of
        bytes.
        
        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.
        
        The signed keyword-only argument determines whether two's complement is
        used to represent the integer.  If signed is False and a negative integer
        is given, an OverflowError is raised.
        """
        pass
    
    def __abs__(self, *args, **kwargs): # real signature unknown
    """ 返回绝对值 """
    
        """ abs(self) """
        pass
    
    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass
    
    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass
    
    def __bool__(self, *args, **kwargs): # real signature unknown
        """ self != 0 """
        pass
    
    def __ceil__(self, *args, **kwargs): # real signature unknown
        """ Ceiling of an Integral returns itself. """
        pass
    
    def __divmod__(self, *args, **kwargs): # real signature unknown
        """
    相除,得到商和余数组成的元组
    Return divmod(self, value). """
        pass
    
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
    
    def __float__(self, *args, **kwargs): # real signature unknown
        """
    转换为浮点类型
    float(self) """
        pass
    
    def __floordiv__(self, *args, **kwargs): # real signature unknown
        """ Return self//value. """
        pass
    
    def __floor__(self, *args, **kwargs): # real signature unknown
        """ Flooring an Integral returns itself. """
        pass
    
    def __format__(self, *args, **kwargs): # real signature unknown
        pass
    
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
    
    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass
    
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
    
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
    
    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass
    
    def __index__(self, *args, **kwargs): # real signature unknown
        """ Return self converted to an integer, if self is suitable for use as an index into a list. """
        pass
    
    def __init__(self, x, base=10): # known special case of int.__init__
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)
        """
        pass
    
    def __int__(self, *args, **kwargs): # real signature unknown
        """ int(self) """
        pass
    
    def __invert__(self, *args, **kwargs): # real signature unknown
        """ ~self """
        pass
    
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
    
    def __lshift__(self, *args, **kwargs): # real signature unknown
        """ Return self<<value. """
        pass
    
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
    
    def __mod__(self, *args, **kwargs): # real signature unknown
        """ Return self%value. """
        pass
    
    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass
    
    def __neg__(self, *args, **kwargs): # real signature unknown
        """ -self """
        pass
    
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
    
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
    
    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass
    
    def __pos__(self, *args, **kwargs): # real signature unknown
        """ +self """
        pass
    
    def __pow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(self, value, mod). """
        pass
    
    def __radd__(self, *args, **kwargs): # real signature unknown
        """ Return value+self. """
        pass
    
    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass
    
    def __rdivmod__(self, *args, **kwargs): # real signature unknown
        """ Return divmod(value, self). """
        pass
    
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
    
    def __rfloordiv__(self, *args, **kwargs): # real signature unknown
        """ Return value//self. """
        pass
    
    def __rlshift__(self, *args, **kwargs): # real signature unknown
        """ Return value<<self. """
        pass
    
    def __rmod__(self, *args, **kwargs): # real signature unknown
        """ Return value%self. """
        pass
    
    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return value*self. """
        pass
    
    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass
    
    def __round__(self, *args, **kwargs): # real signature unknown
        """
        Rounding an Integral returns itself.
        Rounding with an ndigits argument also returns an integer.
        """
        pass
    
    def __rpow__(self, *args, **kwargs): # real signature unknown
        """ Return pow(value, self, mod). """
        pass
    
    def __rrshift__(self, *args, **kwargs): # real signature unknown
        """ Return value>>self. """
        pass
    
    def __rshift__(self, *args, **kwargs): # real signature unknown
        """ Return self>>value. """
        pass
    
    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass
    
    def __rtruediv__(self, *args, **kwargs): # real signature unknown
        """ Return value/self. """
        pass
    
    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass
    
    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Returns size in memory, in bytes """
        pass
    
    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass
    
    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass
    
    def __truediv__(self, *args, **kwargs): # real signature unknown
        """ Return self/value. """
        pass
    
    def __trunc__(self, *args, **kwargs): # real signature unknown
        """ Truncating an Integral returns itself. """
        pass
    
    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass
    
    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the denominator of a rational number in lowest terms"""
    
    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the imaginary part of a complex number"""
    
    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the numerator of a rational number in lowest terms"""
    
    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the real part of a complex number"""
    View Code

    2、布尔值

      真或假
      1 或 0
    3、字符串
    "hello world"
    万恶的字符串拼接:
      python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。
    字符串格式化
    name = "alex"
    print "i am %s " % name
      
    #输出: i am alex

    PS: 字符串是 %s;整数 %d;浮点数%f

    字符串常用功能:  后面有练习
    • 移除空白
    • 分割
    • 长度
    • 索引
    • 切片   
    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
    View Code

      1 可以去除两端空格
    2 可以去除末尾
    3 可以去除 空行
    4 可以传如参数,比如
        n = “hello”
    s = n.strip(“o”)
        print s 结果是 = ‘hell’
    复制代码
    4、列表
    创建列表:
    name_list = ['alex', 'seven', 'eric']
    或
    name_list = list(['alex', 'seven', 'eric'])

    基本操作:

    • 索引
    • 切片
    • 追加
    • 删除
    • 长度
    • 切片
    • 循环
    • 包含
    class list(object):
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        """
        def append(self, p_object): # real signature unknown; restored from __doc__
            """  添加 元素
          L.append(object) -> None -- append object to end """
            pass
    
        def clear(self): # real signature unknown; restored from __doc__
            """  清空元素
        L.clear() -> None -- remove all items from L """
            pass
    
        def copy(self): # real signature unknown; restored from __doc__
            """ 浅copy  L.copy() -> list -- a shallow copy of L """
            return []
    
        def count(self, value): # real signature unknown; restored from __doc__
            """ 匹配 value的个数   L.count(value) -> integer -- return number of occurrences of value """
            return 0
    
        def extend(self, iterable): # real signature unknown; restored from __doc__
            """ 拼接两个列表   L.extend(iterable) -> None -- extend list by appending elements from the iterable """
            pass
    
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """ 返回 某个value 的索引
            L.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    
        def insert(self, index, p_object): # real signature unknown; restored from __doc__
            """ 指定索引位置处添加元素 L.insert(index, object) -- insert object before index """
            pass
    
        def pop(self, index=None): # real signature unknown; restored from __doc__
            """  删除结尾的元素
            L.pop([index]) -> item -- remove and return item at index (default last).
            Raises IndexError if list is empty or index is out of range.
            """
            pass
    
        def remove(self, value): # real signature unknown; restored from __doc__
            """ 移除 从左测匹配的第一个元素
            L.remove(value) -> None -- remove first occurrence of value.
            Raises ValueError if the value is not present.
            """
            pass
    
        def reverse(self): # real signature unknown; restored from __doc__
            """ 反转列表  L.reverse() -- reverse *IN PLACE* """
            pass
    
        def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
            """ 排序 但是int str不行  L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
            pass
    
        def __add__(self, *args, **kwargs): # real signature unknown
            """ Return self+value. """
            pass
    
        def __contains__(self, *args, **kwargs): # real signature unknown
            """ Return key in self. """
            pass
    
        def __delitem__(self, *args, **kwargs): # real signature unknown
            """ Delete self[key]. """
            pass
    
        def __eq__(self, *args, **kwargs): # real signature unknown
            """ Return self==value. """
            pass
    
        def __getattribute__(self, *args, **kwargs): # real signature unknown
            """ Return getattr(self, name). """
            pass
    
        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __ge__(self, *args, **kwargs): # real signature unknown
            """ Return self>=value. """
            pass
    
        def __gt__(self, *args, **kwargs): # real signature unknown
            """ Return self>value. """
            pass
    
        def __iadd__(self, *args, **kwargs): # real signature unknown
            """ Implement self+=value. """
            pass
    
        def __imul__(self, *args, **kwargs): # real signature unknown
            """ Implement self*=value. """
            pass
    
        def __init__(self, seq=()): # known special case of list.__init__
            """
            list() -> new empty list
            list(iterable) -> new list initialized from iterable's items
            # (copied from class doc)
            """
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            pass
    
        def __len__(self, *args, **kwargs): # real signature unknown
            """ Return len(self). """
            pass
    
        def __le__(self, *args, **kwargs): # real signature unknown
            """ Return self<=value. """
            pass
    
        def __lt__(self, *args, **kwargs): # real signature unknown
            """ Return self<value. """
            pass
    
        def __mul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value.n """
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __ne__(self, *args, **kwargs): # real signature unknown
            """ Return self!=value. """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        def __reversed__(self): # real signature unknown; restored from __doc__
            """ L.__reversed__() -- return a reverse iterator over the list """
            pass
    
        def __rmul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value. """
            pass
    
        def __setitem__(self, *args, **kwargs): # real signature unknown
            """ Set self[key] to value. """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ L.__sizeof__() -- size of L in memory, in bytes """
            pass
    
        __hash__ = None
    View Code

    示例:

    复制代码
    ###### 列表 ##########
    
    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    __author__ = 'liujianzuo'
    
    
    lis=[1,2,3,'alex']
    cc=[5,5]
    print(lis.count("alex"))
    lis.extend(cc)
    print(lis)
    
    name_list = ["eirc", "alex", 'tony']
    """
    # 索引
    print(name_list[0])
    # 切片
    print(name_list[0:2])
    # len
    print(name_list[2:len(name_list)])
    # for
    for i in name_list:
        print(i)
    
    
    #join 方法,拼接字符串
    li = ["alex","eric"]
    name = "li jie"
    ss = "_".join(li)
    s = "_".join(name)
    print(s,ss)
    
    
    """
    # 列表内部提供的其他功能
    # append后追加
    name_list.append('seven')
    name_list.append('seven')
    name_list.append('seven')
    print(name_list)
    # 元素出现的次数
    print(name_list.count('seven'))
    # iterable,可迭代的
    temp = [111,22,33,44]
    # 扩展,批量添加
    name_list.extend(temp)
    print(name_list)
    # 获取指定元素的索引位置
    print(name_list.index('alex'))
    # 向指定索引位置插入数据
    name_list.insert(1, 'SB')
    print(name_list)
    # 在原列表中移除掉最后一个元素,并将其赋值给 a1
    a1 = name_list.pop()
    print(name_list)
    print(a1)
    # 移除某个元素
    name_list.remove('seven')
    print(name_list)
    # 翻转
    name_list.reverse()
    print(name_list)
    
    # 删除指定索引位置
    print(name_list)
    del name_list[1:3]
    print(name_list)
    复制代码
    列表表示:key  下表  列表
    root@python:~# python
    Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    列表创建 
    >>> names = ['IBM','Blue Polo','TieZhuang','DaShuai']
    查看列表的值    数字是列表元素的下标
    >>> names[0]
    'IBM'
    >>> names[1]
    'Blue Polo'
    >>> names[2]
    'TieZhuang'
    看最后一个值
    >>> names[-1] 
    'DaShuai'
    
    列表的元素位置取值
    聚合另一个列表
    >>> names.extend(range(1000))   #range(1000)是创建1000个数字的列表,extend是聚合names原来的列表追加上1000个数字
    >>> names  #看全部的值
    
    
    取前十个值
    >>> names[0:9]
    ['IBM', 'Blue Polo', 'TieZhuang', 'DaShuai', 0, 1, 2, 3, 4]
    取后五个值
    >>> names[-5:-1]   #不对
    [995, 996, 997, 998]
    
    >>> names[-5:]    #正确的写法
    [995, 996, 997, 998, 999]
    
    Names的内置函数讲解
    
    Names.append() 追加列表的值
    >>> names.append(559)     #末尾追加559
    >>> names[-3:]       #查看后三位
    [998, 999, 559]
    
    Names.index() 查看列表该值所在的索引位置
    >>> names.index(559)   #查看559 所在的索引位置
    563
    >>> names.insert(500,'IBM')
    >>> names[500]
    'IBM'
    
    找到列表值为559 
    再添加一个559
    >>> names.append(559) 
    看一下有没有
    >>> names[-3:]
    [998, 999, 559]
    看一下索引
    >>> names.index(559) 
    563
    取到值559
    >>> names[names.index(559)]
    559
    names.count()查看列表值的个数
    
    >>> names[-3:]
    [999, 559, 'liujianzuo']
    >>> names.count(559)
    2
    >>> names.count('IBM')     
    2
    Names.insert()指定位置插入值
    >>> names.insert(600,'IBM')
    >>> names.insert(650,'IBM')
    >>> names.count('IBM')     
    4
    names[$index] = ‘key’改列表中某个值为另一个值
    >>> names.index('IBM')
    0
    >>> names[names.index('IBM')]
    'IBM'
    >>> names[names.index('IBM')] = 'IBm'
    >>> names.index('IBm')
    0
    >>> names[0]
    'IBm'
    再次查看 下一个IBM索引变道500了
    >>> names[names.index('IBM')]
    'IBM'
    >>> names.index('IBM')       
    500
    
    练习:批量替换 列表中的IBM 为HP
    root@python:/home/liujianzuo/py_training/seminar6/day2# cat liebiao.py 
    #!/usr/bin/env python
    names = ['IBM','alex','liujianzuo','ddd']
    #names = []
    names.extend(range(1000))
    #naems = names + range(1000)
    names.insert(100,'IBM')
    names.insert(200,'IBM')
    names.insert(300,'IBM')
    
    
    for i in range(names.count('IBM')):
      ibm_index = names.index('IBM')
      print " IBM's INDEX :" ,  ibm_index 
      names[ibm_index] = 'HP'
    print "HP's count num is :" ,names.count('HP')
    
    三个注意 :批量替换 列表中的IBM 为HP:
    1、print格式
    print  “输出描述内容”  逗号   变量
    Print 变量值输出来,如果我要把描述内容放在变量前面,一定要记得加逗号,不然会报错
    root@python:/home/liujianzuo/py_training/seminar6/day2# python liebiao.py 
      File "liebiao.py", line 15
        print "HP's count num is :" names.count('HP')
    
    2、如果要赋值一个空列表
       #names = []
    3、聚合两个列表的另一种方法
    #naems = names + range(1000)
    names.extend(range(1000))
    
    A.pop() a.remove() a.reverse()
    root@python:~# python
    Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    赋值一个列表
    >>> a = range(100)
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
    A.pop()删除最后一个元素
    >>> a.pop()
    99
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
    a.remove(23) 移除列表内容
    >>> import tab
    >>> a.remove(23)
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
    测试remove
    >>> a.insert(23,'IBM')
    >>> a.remove(23)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: list.remove(x): x not in list
    >>> a.index('IBM'
    ... 
    KeyboardInterrupt
    >>> a.index('IBM')
    23
    >>> a.remove('IBM')   
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
    a.reverse() 反转列表元素
    >>> a.reverse()
    >>> a
    [98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    A.sort()排序列表
    数字 大写字母 小写字母
    >>> a.insert(3,5)
    >>> a
    [98, 97, 96, 5, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    >>> a.sort()
    >>> a
    [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
    >>> a.insert(5,'a') 
    >>> a.insert(5,'A')
    >>> a.insert(5,'B')
    >>> a.insert(5,'b')
    >>> a
    [0, 1, 2, 3, 4, 'b', 'B', 'A', 'a', 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
    >>> a.sort()
    >>> a
    [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 'A', 'B', 'a', 'b']
    >>> a.insert(11,'~')
    >>> a.insert(11,'!')
    >>> a.insert(11,'#')
    >>> a.insert(11,'@')
    >>> a
    [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, '@', '#', '!', '~', 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 'A', 'B', 'a', 'b']
    >>> a.sort()
    >>> a
    [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, '!', '#', '@', 'A', 'B', 'a', 'b', '~']
    String方法 
    >>> import string
    >>> string.ascii_letters
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    >>> string.ascii_
    string.ascii_letters    string.ascii_uppercase
    string.ascii_lowercase  
    >>> string.ascii_lowercase
    'abcdefghijklmnopqrstuvwxyz'
    >>> a = string.ascii_lowercase
    >>> a
    'abcdefghijklmnopqrstuvwxyz'
    list(a)将连续的列表做成字符列表
    >>> list(a
    a       all(    any(    as      
    abs(    and     apply(  assert  
    >>> list(a)
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    >>> a.split()
    ['abcdefghijklmnopqrstuvwxyz']
    >>> a
    'abcdefghijklmnopqrstuvwxyz'
    >>> str(a)
    'abcdefghijklmnopqrstuvwxyz'
    >>> a
    'abcdefghijklmnopqrstuvwxyz'
    Join方法将分散的多个元素组成一个元素的列表
    '|'.join(a) 以竖划线为分隔符作为a列表的分割元素分割
    >>> a = list(string.ascii_lowercase)
    >>> a
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    >>> type(a
    a       all(    any(    as      
    abs(    and     apply(  assert  
    >>> type(a)
    <type 'list'>
    >>> str(a)
    "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']"
    >>> 
    >>> str(a)
    "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']"
    >>> a[0]
    'a'
    >>> a[1]
    'b'
    >>> ''.join(a)
    'abcdefghijklmnopqrstuvwxyz'
    >>> '_'.join(a)
    'a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z'
    >>> '|'.join(a)
    'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z'
    >>> a[1]       
    'b'
    
    Str()的用法  例如file是只能写入字符串的我想写入数字
    >>> type(4)
    <type 'int'>
    >>> type(str(4))
    <type 'str'>
    将数组写入文件f.readlines(数组)
    
    >>> f = open('test2.txt','w')
    >>> f.write(5)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: expected a character buffer object
    >>> a
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    >>> f.writelines(a)
    >>> f.close()
    root@python:~# cat test2.txt 
    abcdefghijklmnopqrstuvwxyz
    
    
    程序在写文件的时候还没保存,另一个程序要调用用一个文件如何办
    例如:
    你在vi一个文件的时候,你用python的file方法写了数据到该文件。你vi这个文件无法保存。
    Python写文件系统内核不会给你加锁,而vi枷锁了,例如vi产生一个swp文件
    Python没加 靠自己判断了。
    Python判断文件打开了???
    
    With opne(file) as 别名 不用关闭文件,with语法结束之后文件就关闭。 解决长时间运行程序的方法
    打开文件不要忘记关闭它不要让程序去关闭它,尤其是运行好些天的程序,程序打开了高些文件后,运行几天后,这个程序的cpu就百分之百了。会维护者好几个文件打开者的句柄
    
    
    >>> with open ('test2.txt','r') as f:
    ...   for i in f.readlines():        
    ...     print i              
    ... 
    Abcdefghijklmnopqrstuvwxyz
    
    >>> with open ('test2.txt','a') as f: 
    ...   f.write('
    +++++')
    ... 
    
    Del 删除内存的东西 删除列表的指定内容元素
    >>> a=range(40)
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
    >>> 
    
    >>> del a[6:11]
    >>> a
    [0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
    >>> b=a[7:20]
    >>> b
    [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
    >>> del b
    >>> b
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'b' is not defined
    列表练习

    5、元组
    创建元祖: 元组一旦创建 不等增加也不能减少

     ages = (11, 22, 33, 44, 55) 或 ages = tuple((11, 22, 33, 44, 55)) 

    基本操作:
    索引
    切片
    循环
    长度
    包含

    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__
            """  计算 value的个数  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, *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 __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, 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, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            pass
    
        def __len__(self, *args, **kwargs): # real signature unknown
            """ Return len(self). """
            pass
    
        def __le__(self, *args, **kwargs): # real signature unknown
            """ Return self<=value. """
            pass
    
        def __lt__(self, *args, **kwargs): # real signature unknown
            """ Return self<value. """
            pass
    
        def __mul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value.n """
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __ne__(self, *args, **kwargs): # real signature unknown
            """ Return self!=value. """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        def __rmul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value. """
            pass
    View Code

    示例:

    复制代码
    ############### 元组 #################
    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'))
    复制代码
    元组练习
    复制代码
    不想别人改  默认变量 等。 别人调用你的程序元组。别人该你的不想改 用元组
    只有两个方法
     c.count(
      c.index(
    
    tuple(列表)列表变元组
    >>> a = range(10)
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> d=tuple(a)
    >>> d
    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    list(元组)元组变列表
    >>> d
    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    >>> e = list(a)
    >>> e
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    复制代码
     
    6、字典(无序)
    创建字典:
    person = {"name": "mr.wu", 'age': 18}
    或
    person = dict({"name": "mr.wu", 'age': 18})

    常用操作:

    • 索引
    • 新增
    • 删除
    • 键、值、键值对
    • 循环
    • 长度
    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(*args, **kwargs): # real signature unknown
            """ Returns a new dict with keys from iterable and values equal to value. """
            pass
    
        def get(self, k, d=None): # real signature unknown; restored from __doc__
            """ 根据key获取 d是默认是 为 None   D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
            pass
    
        def items(self): # real signature unknown; restored from __doc__
            """ 将字典的key value都打印成列表元组   D.items() -> a set-like object providing a view on D's items """
            pass
    
        def keys(self): # real signature unknown; restored from __doc__
            """打印字典的key   D.keys() -> a set-like object providing a view on D's keys """
            pass
    
        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
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
            If E is present and lacks a .keys() method, then 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() -> an object providing a view on D's values """
            pass
    
        def __contains__(self, *args, **kwargs): # real signature unknown
            """ True if D has a key k, else False. """
            pass
    
        def __delitem__(self, *args, **kwargs): # real signature unknown
            """ Delete self[key]. """
            pass
    
        def __eq__(self, *args, **kwargs): # real signature unknown
            """ Return self==value. """
            pass
    
        def __getattribute__(self, *args, **kwargs): # real signature unknown
            """ Return getattr(self, name). """
            pass
    
        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __ge__(self, *args, **kwargs): # real signature unknown
            """ Return self>=value. """
            pass
    
        def __gt__(self, *args, **kwargs): # real signature unknown
            """ Return self>value. """
            pass
    
        def __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, *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
    
        @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 __setitem__(self, *args, **kwargs): # real signature unknown
            """ Set self[key] to value. """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ D.__sizeof__() -> size of D in memory, in bytes """
            pass
    
        __hash__ = None
    View Code

    示例: 

    复制代码
    
    
    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    __author__ = 'liujianzuo'


    dic={1:2,"alex":4,4:9}
    print(dic.get("alex"))
    print(dic.items())
    print(dic.keys())
    print(dic.values())
    print(dic.pop(2,None))
    print(dic.setdefault("name","rain"))

    ###################### 字典 ################### # 字典的每一个元素,键值对 user_info = { 0: "alex", "age": 73, 2: 'M' } # 0 “alex" # 1 73 # 索引 # print(user_info[0]) # print(user_info["age"]) # 循环,默认值输出key # for i in user_info: # print(i) # # 获取所有键 # print(user_info.keys()) # # 获取所有值 # print(user_info.values()) # # 获取所有键值对 # print(user_info.items()) # for i in user_info.keys(): # print(i) # # for i in user_info.values(): # print(i) # user_info = { # 0: "alex", # "age": 73, # 2: 'M' # } # for k,v in user_info.items(): # print(k) # print(v) # clear,清除所有内容 # user_info.clear() # print(user_info) # get 根据key获取值,如果key不存在,可以指定一个默认值 # val = user_info.get('age') # print(val) # val = user_info.get('age', '123') # print(val) # 索引取值时,key不存在,报错 # print(user_info['age']) # print(user_info['age1111']) # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断 # ret = 'agfffe' in user_info.keys() # print(ret) # pop # popitem # update # print(user_info) # test = { # "a1": 123, # 'a2': 456 # } # user_info.update(test) # print(user_info) # 删除指定索引的键值对 test = { "a1": 123, 'a2': 456 } del test['a1'] print(test)
    复制代码
     
    示例: 
    
    
    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    __author__ = 'liujianzuo'
    
    
    dic={1:2,"alex":4,4:9}
    print(dic.get("alex"))
    print(dic.items())
    print(dic.keys())
    print(dic.values())
    print(dic.pop(2,None))
    print(dic.setdefault("name","rain"))
    
    ###################### 字典 ###################
    # 字典的每一个元素,键值对
    user_info = {
        0: "alex",
        "age": 73,
        2: 'M'
    }
    # 0   “alex"
    # 1   73
    
    # 索引
    # print(user_info[0])
    # print(user_info["age"])
    
    # 循环,默认值输出key
    # for i in user_info:
    #     print(i)
    
    # # 获取所有键
    # print(user_info.keys())
    # # 获取所有值
    # print(user_info.values())
    # # 获取所有键值对
    # print(user_info.items())
    
    # for i in user_info.keys():
    #     print(i)
    #
    # for i in user_info.values():
    #     print(i)
    
    # user_info = {
    #     0: "alex",
    #     "age": 73,
    #     2: 'M'
    # }
    # for k,v in user_info.items():
    #     print(k)
    #     print(v)
    
    # clear,清除所有内容
    # user_info.clear()
    # print(user_info)
    
    # get 根据key获取值,如果key不存在,可以指定一个默认值
    # val = user_info.get('age')
    # print(val)
    # val = user_info.get('age', '123')
    # print(val)
    # 索引取值时,key不存在,报错
    # print(user_info['age'])
    # print(user_info['age1111'])
    
    
    
    # has_key 检查字典中指定key是否存在   3版本python没有了 可以用in 判断
    # ret = 'agfffe' in user_info.keys()
    # print(ret)
    # pop
    
    # popitem
    
    # update
    # print(user_info)
    # test = {
    #     "a1": 123,
    #     'a2': 456
    # }
    # user_info.update(test)
    # print(user_info)
    
    # 删除指定索引的键值对
    test = {
        "a1": 123,
        'a2': 456
    }
    
    del test['a1']
    print(test)
    
    PS:循环,range,continuebreak
    字典练习
    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:Python27python.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:Python27python.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}
    >>>
    字典练习

    八 for 循环

    1、for循环
    用户按照顺序循环可迭代对象中的内容,
    PS:break、continue
    li = [11,22,33]
    for i in li:
        print(li.index(i),i)

    九 enumrate 

    创建 序列号 

    li = [11,22,33]
    for k,v in enumerate(li, 1):
        print(k,v)

    十 range 和xrange

      迭代循环
      不会先在内存中创建,而是每次循环就创建一次。节约内存。
      3版本python只有range了,等同于xrange
     
    指定范围,生成指定的数字
    复制代码
    print range(1, 10)
    # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
     
    print range(1, 10, 2)
    # 结果:[1, 3, 5, 7, 9]
     
    print range(30, 0, -2)
    # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]


    例如 :
    print(range(1,10))
      输出 range(1, 10) 而不是1 2 3.。。10
     
    复制代码
    复制代码
    range用法:  stop不匹配
    
     range(start,stop,sep)
    
      比如 range(1,10,2)
    
        打印1 3 5 7 9 
    
      range(10,1,-1)
    
          10 9 8 7 ... 2 

    PS:循环,range,continue 和 break

  • 相关阅读:
    编写屏幕保护程序
    C++调用JS函数
    connected standby
    用户层APC队列使用
    WebBrowser2控件使用
    UUID
    网络过滤驱动
    windows短路径转换成长路径
    解析快捷方式指向的文件
    获取进程占用的内存
  • 原文地址:https://www.cnblogs.com/superfangchao/p/8513318.html
Copyright © 2011-2022 走看看