Python Study Notes 2: python Study Notes

Source: Internet
Author: User

Python Study Notes 2: python Study Notes

Chapter 4 for and while Loops

1. for is faster than while. The author of the python learning manual has been restarting to emphasize this.

2. A lot of for usage

A. for x in list:, similar to foreach in C #, but the modification to x cannot change the original value unless x is a reference to the object (if you want to modify the original value, you can only use B for usage, and assign values to list [idx)

B. for idx in range (10):, range can generate an ordered integer assigned to idx. It can have three parameters: range (, 2). The first parameter is the starting value, the second parameter is the next value of the termination value (that is, the value does not contain this value), and the third parameter is the number of increments (that is, the number of increments each time. Here it can also be a negative value for reverse step ), range can be used with len to obtain the index of the list element using: range (len (list ).

C. for item in list [: 2]:, here list [: 2] is a part, and item is an element in each part, the third parameter is also the step number (which can also be negative ). Sharding has the same problem as.

D. for line in open('file.txt ', 'R'):, this usage will get the content in the file line by line.

E. for (x, y) in zip (list, list2):, zip combines the elements with the same index in multiple sequences into a metagroup to generate a list of tuples.

F. for key in Dict: This is equivalent to for key in Dict. keys. It is simplified in the new version. (although it is a bit strange in syntax, it does not enter five characters)

G. for (offset, item) in enumerate (list):, offset gets the index of the iterated object, and item gets its element

H. L = [x + 10 for x in list], list parsing [Results Expression for x in list if x meets the conditions], you can also [x + y for x in 'abc' for y in 'lmn ']. The result is ['al', 'am', 'any', 'bl ', 'bm ', 'bn', 'cl ', 'cm', 'cn']

G. for root, dirs, files in OS. walk (path): traverses the folder. root stores the path of the path root directory, dirs stores the name of the folder under the root directory (without the complete path), and files stores the file name (without the complete path)

3. the for and while statements have one more else block than other languages, only when break is not executed in the loop will the code in the else block be executed (in the past, there were indeed such requirements in programming, it can be seen that python meets the needs of experience)

4. Dict initialization can use zip to simplify dict (zip (keys, values ))

5.zip truncates the result based on the shortest length.

6. map (None, list, list2), map and zip types. The difference is that the vacancy caused by filling the short sequence with the first parameter.

7. file = open('file.txt ', 'R'). There are three reading methods for file.

File. read () # read the entire file (charged for memory)

File. read (1) # read by charactor,file=open('file.txt ', 'rb') followed by file. read (1) indicates reading byte Blocks

File. readline () # read line by line

File. readlines () # read whole file to list include lines

File. xreadlines () # load the text column as needed

8. iterator:

File. readline () is equivalent to executing the iterator file. next (). When file is executed. when next () arrives at the end of the file, a StopException exception will be thrown (for other types of iterators, the iter (list) must be converted)

Sorted (list) # Use iterations to re-sort the list

Sum (list) # Use iterations to add the content of the list element

Any (list) # Use iterations to evaluate all elements or

All (list) # Use iterations to evaluate all elements and

'&'. Join (strlist) # Use iteration to insert among all string elements & get a string

List (listable) # Use iterations to create list objects of iteratable objects

Tuple (listable) # Use iteration to create a new object of the tuples of the iteratable object

9. pass is a null statement.

10. The value assignment statement cannot appear when it should be an expression (this is awesome !) For example, if (x = next () in C language cannot be used in python.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.