ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python之路-2:Python基础

2019-08-07 15:52:27  阅读:198  来源: 互联网

标签:__ None return string Python 之路 self 基础 def


入门拾遗

一、作用域

只要变量在内存中就能被调用!但是(函数的栈有点区别)

对于变量的作用域,执行声明并在内存中存在,如果变量在内存中存在就可以被调用。

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

所以下面的说法是不对的:

外层变量,可以被内层变量使用
内层变量,无法被外层变量使用

二、三元运算

1 result = 值1 if 条件 else 值2

例子:

1 name = raw_input("please input your name: ")
2 if name = "tianshuai":
3     print "you are so shuai!!!"
4 else:
5     print "you are ok"

上面的例子可以用三元运算一句解决:

1 name = raw_input("please input your name: ")
2 shuai = "shuaige" if name == "tianshuai" else "is ok"
3 print shuai

注:循环可以包含循环,列表可以包含列表,元组当然也可以包含元组,字典可以包含字典!思想不要太局限!放开想!

三、python是一门什么语言

编程语言主要从以下几个角度进行分类:

编译型和解释型

静态语言和动态语言

强类型定义语言和弱类型语言

 

编译型和解释型:

编译型,其实他和汇编语言是一样的:也是有一个负责翻译的程序来对我们的源代码进行转换,生成相对应的可执行代码。

这个说的更专业一点,就是编辑(Complie),而负责编译的程序自然就称谓编译器(Compiler)。如果我们写的程序代码都包含在一个源

文 件中,那么通常编译之后就会生成一个可执行文件,我们就直接运行了,而对于一个比较复杂的项目,为了方便管理,我们通常把代码分散在各个原文件中,作为不 通的模块来组织。这是编译各个文件时就会生成目标文件(Objec file)而不是之前所说的可执行文件。一般一个源文件的编译都会对应一个目标文件。这些目标文件里的内容基本上已经是可执行代码了,但是由于只是整个项 目的一部分,所以我们还不能直接运行。待所有的源文件编译都大功告成,我们就可以最后把这些半成品的目标文件“打包”成一个可执行文件了,这个工作由另一 个程序负责完成,由于过程好像是把包含可执行代码的目标文件连接装配起来,所以这个操作又称为连接(Link),而负责连接的程序就叫。。。。。连接程序 (Linker)。连接程序除了连接文件之外,可能还有各种资源,图标文件啊、声音等。连接完成后,一般就可以得到我们降妖的可执行文件了。

 

上面我们大概介绍了编译型语言的特点,现在在看看解释性。从字面上来看“编译”和“解释”都有“翻译”的意思,他们的区别则在于翻译的时机不一样。

打个比方:如果你打算预读一本外文书,而你不知道这么外语,那么你可以找一名翻译,给他足够的时间让他从头到尾把整本书翻译好,

然后把书的母语版交给你阅读。这个过程就编译,或者你也立刻让这名翻译辅助你阅读,让他一句一句的给你翻译,如果你想往回看某个章节他也的重新给你翻译。

 

两 种方式:前者就相当于我们刚才说的编译型:一次把所有的代码转换成机器语言,然后写成可执行文件。

而后者就相当于我们要的节诶实行:在程序运行的前一刻, 还只有源程序而没有可执行程序;而程每执行到资源程序的某一条执行,则会有一个称之为解释程序的外壳程序,将源代码转换成二进制代码以供执行,总而言之就 是不断的解释、执行、解释、执行。。。所以解释型语言是离不开解释程序的。

 

由于程序总是以源代码的形式出现,因此只要有相应的解释器,一直几乎不成问题。编译型程序虽然源代码也可以执行,但前提必须针对不通的系统分别进行编译,对于复杂的工程来说,的确是一件不小的时间小号,而且何忧可能一些细节的地方还有修改源代码。

但是解释性程序省却了编译的步骤,修改调试也非常方便,编辑完毕之后即可运行,不必想编译型语言修改了小小的改动要等很长的Compiling...Linking...

不过凡是有利有弊,由于解释性程序试讲编译的过程放在执行过程中,这就决定了解释性程序注定要比编译型慢上一大截,就想几百倍的速度差距也不足为奇

 

但 既然编译型与解释性各有优缺点又相互对立,所以一批新星的语言都有把两者折中起来的趋势,例如Java语言虽然比较接近解释性语言的特性,但在执行之前预 先进行一次预编译,生成的代码是介于机器码和Java源代码之间的中介码,运行的时候而又JVM(Java的虚拟机平台,可视为解释器)解释执行。他即保 留了源代码的高抽象、可抑制的特点,又已完成了对源代码的大部分预编译工作,所以执行起来比“纯解释性”程序要快的多。宗旨,随着设计技术与硬件的不断发 展,编译型与解释性两种方式的界限正在不断的变模糊

 

 

静态语言和动态语言:

通常我们所说的动态语言、静态语言是指动态类型语言和静态类型语言。

1、 动态类型语言:动态类型语言是指在运行期间才去做数据类型检查的语言,也就是说,在动态类型的语言编程时,永远也不用给任何变量指定数据类型,该语言会在 第一次赋值给变量是,在内部将数据类型记录下来。Python和Ruby就是典型类型的动态类型语言,其他的各种脚本语言如VBScript也多少属于动 态类型语言。

2、静态类型语言:静态类型语言与动态类型语言刚好相反,他的数据类型是在编译期间检查的,也就是说在写程序的时候要声明所有变量的数据类型,C/C++是静态类型的典型代表,其他的静态类型语言还有C#、JAVA等

对于动态语言与静态语言的区分,套用一句比较流行的话是:Static typing when possible,dynamic typing when needed

 

强类型定义语言和弱类型语言

1、强类型定义语言:强制数据类型定义的语言。也就是说,一旦一个变量被指定了某个数据类型,如果不经过强制转换,那么他就永远是这个数据类型了。举个例子:如果你定义了一个整形变量a,那么程序根本不可能讲a当作字符串类型处理。强类型定义语言是类型安全的语言。

2、弱类型定义语言:数据类型可以被忽略的语言。他与强类型定义语言相反,一个变量可以赋予不同数据类型。

 

强类型定义语言在速度上可能略逊色与弱类型定义语言,但是他是强类型定义语言带来的严谨性能够有效便面许多错误,另外,“这么语言是不是动态语言”与“这么语言是否类型安全”之间是完全没有联系的。

例如:Python是动态语言,也是强类型定义语言(类型安全的语言);VBScript是动态语言是弱类型定义语言(类型不安全的语言);

JAVA是静态语言,是强类型定义语言(类型安全的语言)

Python基础

一、整数

如: 18、73、84

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

 int

二、长整型

可能如:2147483649、9223372036854775807

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

 long

三、浮点型

如:3.14、2.88

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

 float

四、字符串

如:'luotianshuai'、'wupeiqi'

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

复制代码
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):  
        """ 子序列位置,如果没找到,则返回-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.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):  
           """ 寻找子序列位置,如果没找到,则异常 """
        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
复制代码

五、列表

如:['shuaige','tianshuai']、['wupeiqi', 'alex']

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

 list

六、元组

如:('shuai','ge','tianshuai')、('wupeiqi', 'alex')

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

 tuple

七、字典

如:{'name': 'luotianshuai', 'age': 18} 、{'host': '2.2.2.2', 'port': 80]}

ps:循环时,默认循环key

每个字典都具备如下功能:

 dict

练习:

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

回答:

复制代码
a=[11,22,33,44,55,66,77,88,99,90]
dict1={'k1':[],'k2':[]}

for i in a:
    if i >66:
        dict1['k1'].append(i)
    else:
        dict1['k2'].append(i)
print dict1

最好的是用下面的方法来动态的扩展字典:
a=[11,22,33,44,55,66,77,88,99,90]
dict1={}  #动态的增加字典

for i in a:
    if i >66:
        if 'k1' in dict1.keys():
            dict1['k1'].append(i)
        else:
            dict1['k1'] = [i,]
    else:
        if 'k2' in dict1.keys():
            dict1['k2'].append(i)
        else:
            dict1['k2'] = [i,]
print dict1
复制代码

 

 

八、set集合

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

 set

练习:

复制代码
 1 练习:寻找差异
 2 # 数据库中原有
 3 old_dict = {
 4     "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
 5     "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
 6     "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
 7 }
 8  
 9 # cmdb 新汇报的数据
10 new_dict = {
11     "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
12     "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
13     "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
14 }
15  
16 需要删除:?
17 需要新建:?
18 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
复制代码

回答:

 

复制代码
#!/usr/bin/env python
#-*- coding:utf-8 -*-


old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
            }

# cmdb 新汇报的数据

new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
            }

for k in new_dict:
    old_dict[k] = new_dict[k]

print old_dict
#也可以用update
old_dict.update(new_dict)
复制代码

 

九、collection系列

1、计数器(counter)

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

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

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

2、有序字典(orderedDict )

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

 OrderedDict

3、默认字典(defaultdict) 

学前需求:

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

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

 defaultdict

4、可命名元组(namedtuple) 

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

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

5、双向队列(deque)

一个线程安全的双向队列

 deque

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

 Queue.Queue

迭代器和生成器

一、迭代器

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

 listiterator

二、生成器

range不是生成器 和 xrange 是生成器

readlines不是生成器 和 xreadlines 是生成器

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

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

复制代码
 1 练习:<br>有如下列表:
 2     [13, 22, 6, 99, 11]
 3  
 4 请按照一下规则计算:
 5 13 和 22 比较,将大的值放在右侧,即:[13, 22, 6, 99, 11]
 6 22 和 6 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]
 7 22 和 99 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]
 8 99 和 42 比较,将大的值放在右侧,即:[13, 6, 22, 11, 99,]
 9  
10 13 和 6 比较,将大的值放在右侧,即:[6, 13, 22, 11, 99,]
11 ...
复制代码

深浅copy

为什么要拷贝?

1 当进行修改时,想要保留原来的数据和修改后的数据

数字字符串 和 集合 在修改时的差异?(深浅拷贝不同的终极原因)

1 2 3 在修改数据时:   数字字符串:在内存中新建一份数据          集合:修改内存中的同一份数据

对于集合,如何保留其修改前和修改后的数据?

1 在内存中拷贝一份

对于集合,如何拷贝其n层元素同时拷贝?

1 深拷贝
复制代码
 1 浅copy
 2 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]}
 3 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]}
 4 >>> dict2 = dict.copy()
 5 
 6 
 7 >>> dict["g"][0] = "shuaige"  #第一次我修改的是第二层的数据
 8 >>> print dict
 9 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
10 >>> print dict2
11 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
12 >>> id(dict["g"][0]),id(dict2["g"][0])
13 (140422980581296, 140422980581296)  #从这里可以看出第二层他们是用的内存地址
14 >>>
15 
16 
17 >>> dict["a"] = "dashuaige"  #注意第二次这里修改的是第一层
18 >>> print dict
19 {'a': 'dashuaige', 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
20 >>> print dict2
21 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
22 >>>
23 >>> id(dict["a"]),id(dict2["a"])
24 (140422980580816, 140422980552272)  #从这里看到第一层他们修改后就不会是相同的内存地址了!
25 >>>
26 
27 
28 #这里看下,第一次我修改了dict的第二层的数据,dict2也跟着改变了,但是我第二次我修改了dict第一层的数据dict2没有修改。
29 说明:浅copy只是第一层是独立的,其他层面是公用的!作用节省内存
30 
31 深copy
32 
33 >>> import copy  #深copy需要导入模块
34 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]}
35 >>> dict2 = copy.deepcopy(dict)
36 >>> print dict
37 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']}
38 >>> print dict2
39 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']}
40 >>> dict["g"][0] = "shuaige"   #修改第二层数据
41 >>> print dict
42 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
43 >>> print dict2
44 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']}
45 >>> id(dict["g"][0]),id(dict2["g"][0])
46 (140422980580816, 140422980580288)  #从这里看到第二个数据现在也不是公用了
47 
48 # 通过这里可以看出他们现在是一个完全独立的,当你修改dict时dict2是不会改变的因为是两个独立的字典!
复制代码

标签:__,None,return,string,Python,之路,self,基础,def
来源: https://www.cnblogs.com/qq3650807/p/11315751.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有