Python Study the next day

Source: Internet
Author: User
Tags extend shallow copy dota

First, the module initial

  • Definition: A module is a file containing the Python definition and declaration, and the filename is the suffix of the module name plus the. Py. Simply put: A py file is a module.
  • Classification:
      • Built-in modules: The Python interpreter comes with it.
      • Custom modules: self-written modules
      • Expansion module: Others write, can be used after installation
  • Import Condition:
    1. The module name must conform to the variable name specification;
    2. The module must be located in the Sys.path module search path.  
  • Import steps:
    • When importing a module, first create a memory space that belongs to you.
    • Load all the code in the module;
    • All variables and methods in the module are stored in the namespace.
  • Module Import Order
    • First built-in modules, followed by expansion modules, and finally custom modules.
  • Module-Imported namespaces
      1. The imported name belongs to the global space, but still points to the memory space where the module's name resides.
      2. The imported name, if it is a function or method, references a global variable.
      3. The imported name does not conflict with the name in the global variable. Similar to re-assignment
      4. Although the imported name belongs to a global variable, the value of the reference variable is still taken from the module.
      5. import* default will import all the names of all the modules into the go global. Import items can be controlled in modules with __all__ = ["A", "B"]
  • From......import ...
      • Comparing import My_module, the namespace ' my_module ' of the source file is brought into the current namespace, and must be used as a my_module. Name.
      • The FROM statement is equivalent to import, and a new namespace is created, but the name in My_module is imported directly into the current global namespace, and the name is used directly in the current namespace.
      • import imported variables or methods, although all belong to Import the global namespace of the file, but whether the function method requires a variable or is called from the original module.

Second, what is PYC

1. Is python an interpreted language?

Python is an explanatory language, and I've been believing it until I find out the existence of the *.pyc file.

If it is an interpreted language, what is the generated *.pyc file? c should be the abbreviation of compiled!

In order to prevent other people who learn python from being misunderstood by this remark, we will clarify this issue in the text and make some basic concepts clear.

 

2. Explanatory and compiled languages

Computers are not able to recognize high-level languages, so when we run a high-level language program, we need a "translator" to engage in the process of translating high-level languages into machine languages that computers can read. This process is divided into two categories, the first of which is compilation, and the second is interpretation.

A compiled language before a program executes, the program executes a compilation process through the compiler, transforming the program into machine language. The runtime does not need to be translated and executes directly. The most typical example is the C language.

The explanatory language does not have this process of compiling, but rather, when the program is running, it interprets the program line by row, then runs directly, and the most typical example is Ruby.

Through the above example, we can summarize the advantages and disadvantages of the explanatory language and the compiled language, because the compiler language before the program has already made a "translation" of the program, so at run time there is less "translation" process, so the efficiency is higher. However, we cannot generalize that some explanatory language can also be optimized by the interpreter to optimize the whole program when translating the program, so that it is close to the compiled language in an efficient and not more than a compiled language.

In addition, with the rise of virtual machine-based languages such as Java, we cannot simply divide the language into two types-----explanatory and compiled.

In Java, for example, Java is first compiled into a bytecode file by a compiler and then interpreted as a machine file by the interpreter at run time. So we say that Java is a language that is compiled and interpreted first.

3. What exactly is Python?

In fact, Python, like java/c#, is also a virtual machine-based language, let's start with a simple look at the Python program's running process.

When we enter Python hello.py on the command line, we actually activate the Python interpreter and tell the interpreter: You're going to start working. But before the "explain", the first thing that actually executes is the same as Java, which is compiled.

Students familiar with Java can consider how we execute a Java program on the command line:

Javac Hello.java

Java Hello

Just when we were using an IDE like Eclipse, we fused these two parts into a piece. In fact, Python is also the same, when we execute Python hello.py, he also executes such a process, so we should describe the Python,python is a first compiled after the interpretation of the language.

4. Brief description of Python's running process

Before we say this question, let's start with two concepts, pycodeobject and PYC files.

The PYC we see on the hard drive naturally doesn't have to say much, and pycodeobject is actually the result of a Python compiler actually compiling it. Let's just get to the bottom of it and keep looking down.

When the Python program runs, the result of the compilation is saved in the Pycodeobject in memory, and when the Python program finishes running, the Python interpreter writes Pycodeobject back to the PYc file.

When the Python program runs for the second time, the program will first look for the PYc file on the hard drive, if found, Determine the last modification time of the. pyc file and the. py file, if the. pyc file is modified later than the. py file, indicating that the source code in the. py file has not been modified, and is directly loaded, otherwise the above procedure is repeated.

So we should be able to locate Pycodeobject and pyc files, we say that PYc file is actually a kind of persistent saving way of pycodeobject.

The main data types of Python are: number, string (String type), Boolean, list, tuple (tuple), and Dictionary (dictionary).

third, the data type1. Numbers (number)

Number includes integers and floating-point numbers

1.1 Creation of numeric types
A = 5b = AB = 10print (a) print (b)

The result is:

A = 5b = 10

1.2 Number type Conversion

var1 = 1.23VAR2 = 4var3 = Int (var1) var4 = Int (var2) print (VAR3,VAR4)

Results:

1 4
python built-in numeric functions2. String type

The string is any text enclosed in single quotes "or double quotes", such as ' qwer ', ' 135 ', and so on. Quotation marks are the representation of a string, not part of a string, there is no difference between single and double quotes in Python, and only in the case of a "Let's Go" in a string like let's go, note that the space is also part of the string.

2.1 Creating a String
1 str1 = ' Hello world! ' 2 str2 = ' Good night! '

String manipulation:

1 #1  * Repeat output String 2 print (' abc ') 3 Result: ABCABC
1 #2  [:] Get the string by index 2 print (' Goodnight ' [2:]) 3 execution result: 4 odnight
1 #3  in member operator if the string contains the given character return True2 print (' Ood ' in ' Goodnight ') 3 execution result: 4 True
1 #4  % formatted output string 2 print (' Tom was a Good boy ') 3 print ('%s was a good boy '% ' Tom ') 4 execution Result: 5 Tom is a good boy6 Tom is a good Do?
1 #5  + string stitching 2 a = ' abc ' 3 b = ' 123 ' 4 C1 = a + b 5 print (C1) 6 execution Result: 7 abc123 8 The method is inefficient and the Join method is efficient: 9 C2 = ". Join ([A, b]) Print (C2) 11 Execution Result: abc123

Python's built-in approach:

python built-in methods3. Boolean values

A Boolean value has only two states, true or false, either true or false. (Note case)

Print (4>2) print (4<2) execution Result: TrueFalse

Boolean values are often used in conditional judgments:

1 num = if num > 3:3     print (' bigger ') 4 else:5     print (' smaller ') 6 execution result: 7 bigger
4. Lists (list)

The list is one of the most commonly used data types in Python, using brackets [] to parse the list. The list makes it easy to store, modify, and manipulate the data.

Definition List

1 lis = [' Tom ', 1, ' Jack ', ' ABC ']

To access the elements in the list by subscript, the index is counted starting at 0

1 >>> lis = [' Tom ', 1, ' Jack ', ' abc ']2 >>> lis[0]3 ' Tom ' 4 >>> lis[1]5 >>> lis[2]7 ' Jac K ' 8 >>> lis[3]9 ' abc '

Some operations:

1. Check ([])

Check

2. Increase (Append.insert)

The Append method is used to append an object to the end of the list, and insert to specify the insertion position.

1 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' Dota '] 2 lis.append (' lol ') 3 print (LIS) 4 execution Result: 5 [' Tom ', ' 1 ', ' Jack ', ' abc ', ' Cat ', ' D Ota ', ' lol '] 6  7 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' Dota '] 8 Lis.insert (1, ' lol ')  

3. Change (re-assign value)

1 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' Dota '] 2 lis[3] = ' Kong ' 3 print (LIS) 4 results: 5 [' Tom ', ' 1 ', ' Jack ', ' Kong ', ' cat ', ' do ' Ta '] 6  7 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' Dota '] 8 lis[0:2] = [' Liu ', ' Mu '] 9 print (LIS) 10 execution result: [' Liu ', ' Mu ', ' Jac K ', ' abc ', ' Cat ', ' Dota ']

4. Deletion (Remove,del,pop)

remove specifies that the element is deleted

1 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' DotA ']2 lis.remove (' Tom ') 3 print (LIS) 4 execution Result: 5 [1, ' Jack ', ' abc ', ' Cat ', ' DotA ']

POP Specifies the subscript to delete, and returns the deleted content, by default deleting the last element

1 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' dota ']2 b = Lis.pop (0) 3 print (LIS) 4 print (b) 5 execution Result: 6 [1, ' Jack ', ' abc ', ' Cat ', ' dota ') ]7 Tom

del Specifies the subscript to delete, you can specify the range to delete

1 lis = [' Tom ', 1, ' Jack ', ' abc ', ' Cat ', ' DotA ']2 del lis[0:3]3 print (LIS) 4 execution Result: 5 [' abc ', ' Cat ', ' DotA ']

5. Other operations

5.1 Count Statistics

1 lis = [' Tom ', ' Jack ', ' abc ', ' Tom ', ' Cat ', ' Dota ']2 print (Lis.count (' Tom ')) 3 execution results: 4 2

5.2 Extend extension, adding all elements of another list at the end of the list

lis = [' Tom ', ' Jack ', ' abc ', ' Tom ', ' Cat ', ' Dota ']a = [' lol ', ' word ']lis.extend (a) print (LIS) execution results: [' Tom ', ' Jack ', ' abc ', ' Tom ', ' cat ', ' Dota ', ' lol ', ' word ']

5.3 Index lists the first occurrence of an element subscript

1 lis = [' Tom ', ' Jack ', ' abc ', ' Tom ', ' Cat ', ' Dota ']2 print (Lis.index (' Tom ')) 3 print (Lis.index (' Jack ')) 4 execution Result: 5 06 1

5.4 Reverse the elements of the list in an inverted order

lis = [' Tom ', ' Jack ', ' abc ', ' Tom ', ' Cat ', ' DotA ']lis.reverse () print (LIS) execution results: [' dota ', ' cat ', ' Tom ', ' abc ', ' Jack ', ' Tom ']

5.5 Sort from large to small, strings sorted by first letter in ASCII table

1 lis = [5,8,2,3,1,9]2 lis.sort () 3 print (LIS) 4 execution Result: 5 [1, 2, 3, 5, 8, 9]

5.6 Copy Copy

Shallow copy

1 names_class1=[' Zhang San ', ' John Doe ', ' Harry ', ' Zhao Liu ', [1,2,3]]2 names_class1_copy=names_class1.copy () 3 print (NAMES_CLASS1) 4 print ( names_class1_copy) 5 Execution results: 6 [' Zhang San ', ' John Doe ', ' Harry ', ' Zhao Liu ', [1, 2, 3]]7 [' Zhang San ', ' John Doe ', ' Harry ', ' Zhao Liu ', [1, 2, 3]
5. Tuples (tuple)

Tuples and lists are similar and are used to save a group of numbers, except that tuples can be created without modification or read-only lists.

Although elements in tuples are not modifiable, the elements in this list can be changed when the list is an element of a tuple.

Grammar

1 names = (' Xiaofang ', ' Laoliu ', ' Cuihua ')

When there is only one element in the tuple, the element is followed by a comma (,)

Name = (' Xiaofang ',)

He has only 2 methods, count and index usage are the same as the list above.

6. Dictionary (Dictionary)

A dictionary is the only type of mapping in Python that stores data in the form of key-value pairs (key-value). Python computes the hash function of key and determines the storage address of value based on the computed result, so the dictionary is stored out of order and the key must be hashed. A hash indicates that a key must be an immutable type, such as a number, a string, a tuple.

The Dictionary (dictionary) is the most flexible built-in data structure type in addition to the list of unexpected python. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by subscripts.

Create a dictionary

1 dic1={' name ': ' Xiaoliu ', ' age ':, ' sex ': ' Male '}2 dic2=dict ((' Name ', ' Xiaoliu '),) 3 print (DIC1) 4 print (DIC2) 5 Execution Result: 6 {' Age ': +, ' name ': ' Xiaoliu ', ' sex ': ' Male '}7 {' name ': ' Xiaoliu '}

Operation:

1. Check

1 dic={' name ': ' Xiaoliu ', ' age ':, ' sex ': ' Male '} 2 print (dic[' name ']) 3 print (dic[' names '])  #没有键报错 4 Execution Result: 5 Xiaoliu 6 Keyerror: ' names ' 7  8 dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '} 9 print (Dic.get (' age ')) print (Dic.get (' ages ')  #没有键返回None11 execution results: 2713 None14 dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '}16 print (Dic.items ()) + Print (Dic.keys ()) print (Dic.values ()) Print (List (Dic.keys ())) 20 Execution Result: Dict_items ([' Age ', ' + '), (' Name ', ' Xiaoliu '), (  ' Sex ', ' male ')] Dict_keys ([' Age ', ' name ', ' Sex ']) ([[26, ' Xiaoliu ', ' Male ']) [' name ', ' sex ', ' age ']25 Print (' name ' in dic) 27 execution Result: True

2. Increase

1 dic3 = {} 2 dic3[' name '] = ' xiaoliu ' 3 dic3[' age '] = 4 print (DIC3) 5 Execution Result: 6 {' name ': ' Xiaoliu ', ' age ': + 7  8 A = Dic3.setdefault (' name ', ' Yuan ') 9 B = dic3.setdefault (' Age ', "ten") print (A, b) print (DIC3) 12 execution Result: Xiaoliu 1814 {' Name ': ' Xiaoliu ', ' Age ': 18}

3. By deleting

1 dic={' name ': ' Xiaoliu ', ' age ':, ' sex ': ' Male '} 2 dic.clear ()  #清空字典 3  4 del dic[' name '] 5 print (DIC) 6 execution Result: 7 {' SE X ': ' Male ', ' age ': 8  9 del dic #删除字典10 each  a = Dic.pop (' name ')  #删除选中的键和值 and return value of "Print (A,dic) 13 results: + Xiao Liu {' sex ': ' Male ', ' age ': 27}15 a = Dic.popitem ()  #任意删除一组键值, and returns the key value of the print (a,dic) 18 Execution Result: (' name ', ' Xiaoliu ') {' A GE ': ' Sex ': ' Male '}

4. Change

1 dic={' name ': ' Xiaoliu ', ' age ':, ' sex ': ' Male '} 2 dic[' name '] = ' Liyang ' 3 print (DIC) 4 execution Result: 5 {' name ': ' Liyang ', ' sex ': ' Male ', ' age ': $6  7 dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '} 8 Dic1 = {' Hobby ': ' Girl ', ' age ': +}  # DiC did not add the same key to the Update 9 dic.update (DIC1) of the print (DIC) 11 execution result: {' name ': ' Xiaoliu ', ' age ': ' Hobby ': ' Girl ', ' sex ': ' Male '}

5. Other operations and methods

5.1 Dict.fromkeys ()

1 D1 = Dict.fromkeys ([' name1 ', ' name2 ', ' Name3 '], ' Tom ') 2 D2=dict.fromkeys ([' host1 ', ' host2 ', ' host3 '],[' Mac ', ' Huawei ') ) 3 Print (D1) 4 print (D2) 5 Execution Result: 6 {' name2 ': ' Tom ', ' Name3 ': ' Tom ', ' name1 ': ' Tom '}7 {' host3 ': [' Mac ', ' Huawei '], ' host1 ': [' Mac ', ' Huawei '], ' host2 ': [' mac ', ' Huawei ']}

5.2 d.copy () shallow copy of the dictionary, returns a new dictionary with the same key-value pair as D

5.3 Nesting of dictionaries

1 dic = {' city ': {' Beijing ': ' Chaoyang ', ' Shanghai ': ' Pudong '},2        ' fruit ': [' banana ', ' apple '], ' country ': ' Chinese '}3 Print (dic[' city ' [' Beijing ']) 4 execution Result: 5 Chaoyang

5.4 Traversal of the dictionary

1 dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '} 2 for I in Dic:3     print (I,dic[i]) 4 execution Result: 5 name Xiaoliu 6 Sex male 7 A GE 8  9 dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '}10 for item in Dic.items ():     print (item) 12 Execution Result: 13 (' Name ', ' Xiaoliu ') (' age ', ' + ') (' sex ', ' male ') "dic={' name ': ' Xiaoliu ', ' age ': +, ' sex ': ' Male '}18 for key,values in D Ic.items ():     print (key,values) 20 execution result: Age 2722 sex male23 name Xiaoliu

5.5 Sorted (DIC) arranges dictionary keys in an orderly fashion into a dictionary.

1 dic={5: ' 555 ', 2: ' 222 ', 4: ' 444 '}2 print (sorted (DIC)) 3 >>>4 [2,4,5]
7. Collection

A collection is a set of unordered, non-repeating elements that is the basic data type of Python. The primary function of a set is to de-weigh and test the relationship.

The collection is represented by braces "{}", but an empty collection cannot be represented by "{}", but only with set (), which creates an empty dictionary.

1 SE1 = {}2 Se2 = set () 3 print (Type (SE1)) 4 print (Type (SE2)) 5 >>>:6 <class ' dict ' >7 <class ' Set ' >

1. The elements in the collection must be hashed

1 SE = {[1,2],3,4}2 print (SE) 3 >>>:4 typeerror:unhashable type: ' List '

2. Go to the heavy

1 SE = {1,3,4,1,5, ' a ', ' a ', ' C ', ' C ', ' B ', 5}2 print (SE) 3 >>>:4 {1, ' C ', 3, 4, 5, ' A ', ' B '}
1 se = ' aabbccddee ' 2 SE1 = set (SE) 3 print (SE1) 4 >>>:5 {' C ', ' d ', ' B ', ' e ', ' a '}

3. Relationship Testing

1 A = set ([1,2,3,4,5]) 2 B = Set ([3,4,5,6,7]) 3  4 #父集 5 print (a > B) #>>>:false  A is not in B, 6 print (A in B) #>>>:false  A is not in B 7 print (b > a) #>>>:false  B is not in a medium 8 print (b in a) #>>>:false  b Not in a 9 #差集11 print (a.difference (b)) #>>>:{1, 2}  in a not B12 print (A-a) #{1, 2}13 print (B.difference (a)) #>>>:{6, 7}  in B not A15 print (b-a) #{6, 7}16 print (a.symmetric_difference (b)) #>>>:{1, 2, 6, 7}
   
     symmetric difference set, inverse intersection of print (a ^ b) #>>>:{1, 2, 6, 7}19 #并集21 print (a.union (b)) #>>>:{1, 2, 3, 4, 5, 6, 7}22 PR  int (A | b) #>>>:{1, 2, 3, 4, 5, 6, 7}23 #交集25 print (a.intersection (b)) #>>>:{3, 4, 5}26 print (A & b) #>>>:{3, 4, 5}
   

Python Study the next day

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.