Python road -2: Python basis

Getting Supplements

First, the scope

As long as the variables can be called in memory! But (stack function of a little difference)

For the scope of the variable, and there is a statement executed in memory, if the variable exists in memory can be called.

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

So the following statement is wrong:

Variable layer, the inner layer may be a variable 
inner variable, the variable can not be used an outer layer

Second, ternary operator

1 result = value 2 value 1 if the condition else

example:

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"

The above example can be solved by a ternary operator:

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

Note: The cycle may contain cycles, the list can include lists, tuples, of course, can also contain tuples, dictionaries may contain dictionary! Do not thought too limited! I want to let go!

Three, python is a language what

The main programming language to classify from the following perspectives:

Compiled and interpreted

Static and dynamic languages

Strongly typed language and weakly typed language

 

Compiled and interpreted:

Compiled, in fact, he and assembly language is the same: there is also a program to convert responsible for the translation of our source code to generate the corresponding executable code.

This says little more professional, is to edit (Complie), which is responsible for compiling the appellation naturally compiler (Compiler). If we write the program source code is contained in a

File, it will generate an executable file after compiling usually, we just ran, and for a more complex project, in order to facilitate the management, we usually put the code scattered in various original documents, as a module does not make sense to organize . This is said before it will generate an object file (Objec file) when you compile each file instead of an executable file. General will compile a source file corresponds to a target file. These objects are basically the contents of executable code, but because only part of the whole project, so we can not directly run. All source files to be compiled are done, we can finally put these semi-finished object files "packaged" into a single executable file, this work is responsible for the completion of another program, because the process seems to be the object files contain executable code assembled connector, so this operation is also known as connection (Link), which is responsible for the call to connect. . . . . Linker (Linker). In addition to the connection file connection program, there may be a variety of resources, the icon file ah, sound and so on. Once connected, you can generally get our subdue executable files.

 

Above we probably introduces the features of compiled languages, now look explanatory. Literally "Compile" and "interpretation" have the "Translate" means, the difference between them lies in the timing of translation are not the same.

An analogy: If you intend to pre-read a foreign instrument, so you do not know a foreign language, then you can find a translator, give him enough time for him to translate the entire book from start to finish to a good,

Then the native language edition of the book read to you. This process is to compile, or you immediately so that the name translation assistance you read, let him give you the translation of a sentence, if you want to look back a chapter he also re-give you the translation.

 

In two ways: the former is equivalent to saying that we have just compiled: time to convert all the code into machine language, and then written in the executable file.

The latter is equivalent to section eh we want to implement: Before running the moment, there are only source code but not an executable program; and the implementation process every resource to execute a certain program, then there will be a call interpreter the shell, converts the source code into binary code for execution, all in all is constantly interpretation, execution, interpretation, execution. . . So interpreted language is inseparable from the interpreter.

 

Because the program is always in the form of source code, so long as the appropriate interpreter, has been almost no problem. Although the compiled program source code can be executed, but the premise must be compiled separately for barrier systems for complex projects, it is indeed a big time trumpet, and He You may also modify some details of the place source code.

However interpretative program eliminates the step of compiling, debugging is also very easy to modify, to run after the editing is completed, do not want to modify the compiled languages ​​such as small change for a very long Compiling ... Linking ...

But all pros and cons, because the process of compiling an explanatory lecture program on the implementation process, which determines the interpretive program destined compiled slower than on a large, wanted to hundreds of times the speed gap is also a cause for odd

 

But since compiled and interpretive have advantages and disadvantages and against each other, so the language has a number of star to compromise both up trends, such as the Java language, although relatively close to the explanatory language features, but in advance before execution a pre-compiler, the generated code is code between the intermediary between the Java source code and machine code, but time is running JVM (Java virtual machine platform that can be regarded as interpreter) interpreted. He retains the high level of abstraction of the source code, can inhibit the characteristics, but also has completed most of the work on the pre-compiled source code, so execute much faster than the "purely interpretive" program. Purpose, with the continuous development of design technology and hardware, compiled and interpretive boundaries are two ways of being constantly blurred

 

 

Static and dynamic languages:

Usually what we call dynamic languages ​​and static language is a dynamically typed language and a statically typed language.

1, dynamically typed languages: dynamically typed language is the only language data type checking is done during operation, that is, when dynamically typed programming language, will never need to specify the data type of any variable, the language will be the first assigned to a variable, in the internal data type recorded. Python and Ruby is a typical type of dynamically typed languages, various other scripting languages ​​such as VBScript also how many of dynamically typed languages.

2, statically typed languages: statically typed language with dynamically typed languages ​​just the opposite, his data type checking at compile time, which means that the written procedures to declare the data types of all variables, C / C ++ is a statically typed a typical representative of other statically typed languages ​​as well as C #, JAVA, etc.

For the distinction between dynamic languages ​​and static languages, to paraphrase a popular saying is: Static typing when possible, dynamic typing when needed

 

Strongly typed language and weakly typed language

1, strongly typed language: mandatory data type definition language. That is, once a variable is assigned a data type, if not through coercion, then he will always be this type of data. For example: if you define an integer variable a, it is impossible to talk about a program as a string type of treatment. Strongly typed language is type-safe language.

2, the weak type definition language: data types of languages ​​can be ignored. He and strongly typed language contrast, a variable can be given different data types.

 

Strongly typed language may be slightly inferior in terms of speed and weak type definition language, but he is a strongly typed language brings rigor will be able to effectively face many errors, in addition, "such language is not a dynamic language" and whether "such a language between the type of security "is no link.

For example: Python language is dynamic, is strongly typed languages ​​(type-safe languages); VBScript dynamic languages ​​are weakly typed definition language (language unsafe type);

JAVA is a static language, is a strongly typed language (type-safe language)

Python basis

First, integer

Such as: 18,73,84

Each integer all have the following features:

  int

Second, long integer

Might as: 2147483649,9223372036854775807

Long are each provided with the following functions:

  long

Third, the float

Such as: 3.14,2.88

Each float will have the following functions:

  float

Fourth, the string

如: 'luotianshuai', 'wupeiqi'

Each string includes the following functions:

Copy the code
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):  
        "" "Sequence position, if not found, or -1 is returned." "" 
        S.find (Sub [, Start [, End]]) -> int 
        
        the Return The Lowest Sub index in the substring S WHERE IS found, 
        SUCH that Sub Contained WITHIN S IS. [Start: End] Optional The 
        arguments Start and End are Interpreted AS Slice Notation in. 
        
        the return -1 ON failure. 
        "" " 
        return 0 

    DEF the format (* args, ** kwargs): # Known Special Case of STR .format 
        "" "format string, dynamic parameters, when the elaborate functional programming" "" 
        "" " 
        S.format (* args, ** kwargs) -> string 
        
        the Return formatted A Version of S, from the using Substitutions 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):  
        """Whether it is the letter "" " 
        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):  
        """Segmentation, maxsplit split up to several "" " 
        " ""
        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"
        Transformation, we need to do first a correspondence table, a means to delete the last set of characters
        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
Copy the code

V. List

Such as: [ 'shuaige', 'tianshuai'], [ 'wupeiqi', 'alex']

Each list has the following features:

  list

Sixth, the tuple

As :( 'shuai', 'ge', 'tianshuai'), ( 'wupeiqi', 'alex')

Each tuple has the following features:

  tuple

Seven dictionary

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

ps: the cycle, the default cycle key

Each dictionary will have the following functions:

  dict

Exercise:

Exercise 1: classification element 
2 has the following set of values [11,22,33,44,55,66,77,88,99,90 ...], all values greater than 66 will be saved to the first key in the dictionary the saved value to a value less than 66 in the second key. 
I.e. 3: { 'k1': greater than 66, 'k2': less than 66}

Reply:

Copy the code
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
Copy the code

 

 

八、set集合

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

  set

练习:

Copy the code
 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 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
Copy the code

回答:

 

Copy the code
#!/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)
Copy the code

 

九、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创建,即:对于生成器只有使用时才创建,从而不避免内存浪费

Copy the code
 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 the code

深浅copy

为什么要拷贝?

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

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

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

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

1
在内存中拷贝一份

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

1
深拷贝
Copy the code
 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 (140,422,980,580,816, 140,422,980,580,288) # here to see the second data now is not a public 
47 
48 # Here they can be seen now is a fully independent, when you change the dict dict2 will not change because it is two independent dictionary!
Copy the code

Guess you like

Origin www.cnblogs.com/qq3650807/p/11315751.html