Python Learning notes Summary (i) Summary of objects and process statements

Source: Internet
Author: User

I. Type of Object
1. Digital
Number: Non-volatile
2. String
String: Do not modify "modify need to create new object", have order, support length (len), merge (+), repeat (*), index s[0], shard (S[1:3], member test (in), iteration (for);
Unique find finds, replacement replace, split split; supports list (s) to break a string into a list of characters, tuple (s) breaks the string into tuples of one character, copies the available shards and copy standard library,
Sorting sort and delete del are not supported (because they cannot be modified in situ)
3, meta-group
Tuples: Can not be modified in place, have order, support for length (len), merge (+), repeat (*), index t[0], shard T[2:-1], member test (in), Iteration (for), can nest lists, dictionaries, tuples,
A list (T) is supported to convert a tuple to a matrix, and a new object is generated when converted. Copy the available shards and copy standard libraries; Do not support sorting sort and delete del (immutable) "No Method"
Note: The immutability of tuples is only applicable to the internal list of tuples with the top level of the tuple itself rather than its contents, and the dictionary can be modified as usual.
4. List
List: can be modified in situ, with order, support for length (len), merge (+), repeat (*), index l[0], shard L[0:3], member test (in), Iteration (for), contains any object, can be nested list, dictionary, tuple.
Variable representation in support of adding a single object: L.append (4), adding multiple objects: l.extend ([5,6,7]), inserting X:l2.insert (i,x) at I position, Index assignment: l2[i]=1, Shard assignment: l2[i:j]=[4,5,6]
Remove data (Parameter object): L.remove (' B '), removing data (parameter sequence): L.pop (' B '), cropping index: del l[k], cropping shard del l[i:j], clipping list: Del L,
Sort: l2.sort (), Reverse order: L.reverse (), object Lookup by Object index (opposite to index): L.index (' abc '), copy of available shards and copy standard library
Support Rang (start, start, step) Create a list
Support List (L) itself
You can convert a list to a tuple: T=tuple (L) #转换的时候生成新的对象.
You can convert a tuple to a list: list (T) #产生新的列表对象
You cannot first create an empty list and then add elements.

List parsing
>>> l=[1,2,3,4,5]
>>> l=[x+10 for x in L]
Remove a line break from a row in a list
>>> Lines=[line.rstrip () for line in lines]
>>> Lines=[line.rstrip () for line in open ('/etc/rc.conf ')]
Extended List Resolution
Repeat the previous example, but we just need to start with a line of text that is not a #.
>>> Lines=[line.rstrip () for line in open ('/etc/rc.conf ') if line[0]!= ' # ')
A complete statement can accept any number of for clauses, and each partition can be combined with an optional if clause
>>> [x+y for x in ' abc ' for Y in ' LMN ']
[' Al ', ' am ', ' an ', ' bl ', ' bm ', ' bn ', ' cl ', ' cm ', ' cn ']
Creates a list of X+y merges for each x in a string, and for each y in another string. Collection of two string character permutation combinations


5. Dictionaries
Dictionary: can be modified in place [by key modification], no order, support for length (len), index d[' name '], member test (in), Diego (for) (Keys,values method returned list support), Del d[' name '],del D,
Does not support merging, repeating, sharding, containing any object, can nest lists, dictionaries, tuples. Sorting sort is not supported.
List (D) is supported, and copy of Dictionary key is available. Dcopy (), Copy standard library
You can create an empty dictionary, and then add elements.
>>> d={}
>>> d={' one ': 1}
>>> D
{' One ': 1}
The list cannot be added by this method, the list can only be modified by the Append method, and the list can modify the data of the existing sequence by means of l[1]= ' A '.

6. Contrast
Object flexibility
* Lists, dictionaries, tuples can contain objects of any kind.
* list, dictionary, tuple can be nested arbitrarily
* Lists, dictionaries can be expanded and scaled up dynamically.
Some places do need to be copied, so you can clearly ask
* Shard expression without constraints (l[:]) to assign a sequence of values
* Dictionary Copy Method (D.copy ()) to copy a dictionary
* Write built-in functions (for example, list) to produce copies (list (L))
* Copy standard library module to generate full copy

Two, assignment expressions and printing
1. Assignment operation
Variable naming rules
Statement: (underscore or letter) + (any number of letters, numbers, or underscores)
Note: Case-sensitive, forbidden to use reserved words, and preceded by an underscore variable name (__x__) is a system-defined variable name that has special meaning for the interpreter
The variable name does not have a type, but the object has

Operation interpretation
Diege= ' Diege ' basic form
Diege,lily= ' yum ', ' Wang ' tuple assignment operation (positional) Sequence assignment statement
[diege,lily]=[' yum ', ' yum '] list assignment operation (positional) Sequence assignment statement
A,B,C=STRING[0],STRING[1],STRING[2] Advanced Assignment
(b), c) = (' DI ', ' GE ') can be assigned a nested sequence
A,b,c,d= ' Dieg ' #序列赋值运算, the versatility #MS不行, the quantity must be consistent. Sequence Assignment Statements
Name=uname= ' Diege ' multi-objective assignment operation
Diege + = 43 Enhanced assignment operation (equivalent to diege=diege+43)
2. Introduction of expression Statements
In Python, you can use an expression as a statement (one line in itself). However, because the expression results are not stored, it makes sense only if the expression works and acts as an additional effect.
Typically, expressions are used as statements in two cases.
* Calling functions and methods
Some functions and methods do a lot of work without returning a value, which is sometimes called a process in other languages. Because they don't return the values you might want to keep, you can call them with an expression statement.
* Print values at the interactive mode prompt
Common Python expression statements
Operation interpretation
Spam (Eggs,ham) function call
Spam.ham (eggs) method call
Spam printing variables within the interactive mode interpreter
Spam < ham and ham! = eggs Conforming Expression
Spam < Ham < eggs-range expressions
Note: Although the expression can appear as a statement in Python, the statement cannot be used as an expression.

Expression statements and in situ modifications
Calling Append,sort,reverse on a list this kind of meta-calculation, which is modified in place, must be a modification of the list in place, but these methods will not return the list after the list has been modified.

3. Printing
>>>print ' Diege,test ' #把对象打印至sys. StdOut, add a space between elements, and add line breaks at the end.
>>> name= ' Diege '
>>> age=18
>>> print ' My name is:%s age is:%s '% (name,age)
My name Is:diege age is:18

Print X is equivalent to
Import Sys
Sys.stdout.write (str (x) + ' \ n ')
When the print statement starts with >>, followed by the output file object (or other object), the print statement passes the text to the object's write method, but does not reset the sys.stdout. Because this redirection is temporary. The normal print statement will continue printing to the original output stream.
>>> log=open (' Log.txt ', ' a ', 0)
>>> x,y,z=10,11,12
>>> Print >> Log,x,y,z
>>> Print >> output file, input,, content

Third, the process statement
1. While loop
While <test>:
<statements1>
If <test2>:break
If <test3>:continue
If <test4>:p
Else
<statements2>
Break
Jump out of the nearest loop (jump out of the entire loop statement)
Continue
Jumps to the beginning of the nearest loop (to the first line of the loop, skipping this cycle)
Pass
Don't do anything, just empty placeholder statements
Loop Else block
Executes only if the loop is normally left (that is, no break statement is encountered)
2. For loop
The For loop is a generic sequence iterator in Python: You can traverse elements within any ordered sequence object. The For statement can be used for strings, lists, tuples, other built-in iterative objects, and new objects that we can then create through the class.
The first line of the For Loop defines an assignment target (or "some target"), and the object you want to traverse, followed by the block of statements you want to repeat (usually indented).
When Ptyhon runs a for loop, the elements in the sequence object are assigned to the target individually, and then the loop body is executed for each element.
For <target> in <object>:
<statements>
If <test>:break
If <test>:conitnue
Else
<statements>
Multiple layers can be nested
Three-dimensional expression

A=y if X else Z
Expression Y is executed only if X is true, and expression Z is executed only if X is False

3. iterators
The For loop can be used with any "object that can be iterated". These iterative tools include for loops, list parsing, in-member relationship testing, and map built-in functions.
Next () file iteration method, without having to read the file.
The best way to read text row by line is not to read at all, its alternative is to have the For loop automatically calls next in each round to advance to the next line
>>> for line in open ('/etc/rc.conf '):
... print Line.upper (),
Dictionary iterations
>>> for key in D:
... print Key,d[key]
Other iterative environments
List parsing
[Line.upper () for line in open ('/etc/rc.conf ')]
In member relationships
Map built-in functions and other built-in tools (such as Sorted,sum)
Map (Str.upper,open ('/etc/rc.conf '))
>>> Sorted (open ('/etc/rc.conf ')) #这个工具排序了, newer built-in functions with iterative protocols. Applied to any object that can be iterated.
>>> sum ([3,5,6,9]) #sum调用会计算任何可迭代对象内所有数字的和
23
List and tuple built-in functions (Create new objects from an iterative object), string join methods (to put substrings between strings within an iterative object), and sequence assignment statements.
>>> List (open ('/etc/rc.conf '))
>>> Tuple (open ('/etc/rc.conf '))
>>> ' && '. Join (Open ('/etc/rc.conf '))
>>> a,d,c,d=open ('/etc/rc.conf ')
4. Techniques for Writing Loops
When traversing a sequence, the For loop is preferred, and the For loop includes most counter-style loops, for which is easier to write and faster to execute.
Python provides two built-in functions for customizing iterations within A For loop:
* The built-in range function returns a list of consecutive integers that can be used as an index in for.
>>> Range (5,10,2)
[5, 7, 9]
>>> Range (5,-5,-1)
[5, 4, 3, 2, 1, 0,-1,-2,-3,-4]
Try to use a simple for loop, do not use a while, and do not make a range call in the For loop, just consider it the last choice, and the easier way is always better.
>>> for I in X:
... print I
For x in S[::2]:p rint x# Step 2
* The built-in zip function returns a list of parallel element tuples that can be used to traverse several sequences in for
Parallel traversal: Zip and map
>>> l1=[1,2,3,4]
>>> l2=[5,6,7,8]
>>> Zip (L1,L2)
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> for (x, y) in Zip (L1,L2):
... print x, y, '---', x+y
When the parameter length is not the same, the zip truncates the resulting tuple with the length of the shortest sequence:
The built-in map function matches the elements of the sequence in a similar way, but if the length of the argument is different, it will be used for a shorter sequence with none.
>>> Map (NONE,S1,S2)
[(' A ', ' X '), (' B ', ' Y '), (' C ', ' Z '), (None, ' 1 '), (None, ' 2 '), (None, ' 3 ')]
Using the Zip construction dictionary
>>> keys=[' name ', ' Age ', ' class '
>>> vals=[' Diege ', 18,2012]
>>> dict (Zip (keys,vals))
{' Age ': +, ' name ': ' Diege ', ' Class ': 2012}
>>> d5=dict (Zip (keys,vals))
Enumerate built-in functions that produce offsets and elements
>>> s= ' Diege '
>>> for (Offset,item) in Enumerate (S):
... print Item,offset
...
D 0
I 1
This method has a next method, and each time the list is traversed, a tuple (Index,value) is returned, and we can decompose it by tuple assignment operations in for.
>>> e=enumerate (S)
>>> E.next ()
(0, ' d ')
>>> E.next ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
Stopiteration
5. List parsing
List parsing is written in square brackets, because it is, after all, a way to create a new list.
[expression ' for X ' in L ' for loop header]
List parsing
>>> l=[1,2,3,4,5]
>>> l=[x+10 for x in L]
Remove a line break from a row in a list
>>> Lines=[line.rstrip () for line in lines]
>>> Lines=[line.rstrip () for line in open ('/etc/rc.conf ')]
Extended List Resolution
Repeat the previous example, but we just need to start with a line of text that is not a #.
>>> Lines=[line.rstrip () for line in open ('/etc/rc.conf ') if line[0]!= ' # ')
A complete statement can accept any number of for clauses, and each partition can be combined with an optional if clause
>>> [x+y for x in ' abc ' for Y in ' LMN ']
[' Al ', ' am ', ' an ', ' bl ', ' bm ', ' bn ', ' cl ', ' cm ', ' cn ']
Creates a list of X+y merges for each x in a string, and for each y in another string. Collection of two string character permutation combinations

Python Learning notes Summary (i) Summary of objects and process statements

Related Article

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.