For Loop details in Python

Source: Internet
Author: User

Like most other languages, Python also has a for loop. The only reason you haven't seen them yet is that Python is doing well in many other ways, And you usually don't need them.

Most other languages do not have the list data type as powerful as Python, so you need to do a lot of things in person, specifying the start, end, and step size, to define integers, characters, or other repeated entities in a certain range. However, in Python, A for loop simply loops through a list, which works in the same way as list parsing.

1. for Loop Introduction

Copy codeThe Code is as follows:
>>> Li = ['A', 'B', 'E']
>>> For s in li: (1)
... Print s (2)
A

E
>>> Print "\ n". join (li) (3)
A

E

(1) the syntax of the for Loop is similar to that of list parsing. Li is a list, and s receives the values of each element in sequence from the first element.
(2) Like an if statement or any other indent block, a for loop can contain any number of lines of code.
(3) This is why you have never seen the for loop before: So far we do not need it. It is surprising that when you want only join or list parsing, you often need to use the for Loop in other languages.

It is also very easy to create a "normal" (Visual Basic Standard) counting for loop.

2. Simple count

Copy codeThe Code is as follows:
>>> For I in range (5): (1)
... Print I
0
1
2
3
4
>>> Li = ['A', 'B', 'C', 'D', 'E']
>>> For I in range (len (li): (2)
-104-Dive Into Python http://diveintopython.org/
... Print li [I]
A

C
D
E

(1) range generates a list of Integers to control the loop. I know it looks strange, but it is useful for counting loops occasionally (I just say occasionally.
(2) We never used it that way. This is the Visual Basic style of thinking. Get rid of it. The method for correctly traversing the list is shown in the previous example.

A for Loop is not only used for simple counting. They can traverse anything of any type. The following example uses a for loop to traverse a dictionary.

3. Traverse dictionary
Copy codeThe Code is as follows:
>>> Import OS
>>> For k, v in OS. environ. items (): (1) (2)
... Print "% s = % s" % (k, v)
USERPROFILE = C: \ Documents ents and Settings \ mpilgrim
OS = Windows_NT
COMPUTERNAME = MPILGRIM
USERNAME = mpilgrim
[...]
>>> Print "\ n". join (["% s = % s" % (k, v)
... For k, v in OS. environ. items ()]) (3)
USERPROFILE = C: \ Documents ents and Settings \ mpilgrim
OS = Windows_NT
COMPUTERNAME = MPILGRIM
USERNAME = mpilgrim
[...]

(1) OS. environ is a dictionary of the environment variables defined on your system. In Windows, these variables are user and system variables that can be accessed from the MS-DOS. In UNIX, they are the export (output) variables in your shell STARTUP script. In Mac OS, there is no environment variable concept, so this dictionary is empty.
(2) OS. environ. items () returns a tuple list: [(key1, value1), (key2, value2),...]. The for loop traverses the list. In the first round, it assigns key1 to k and value1 to v, So k = USERPROFILE, v = C: \ Documents ents and Settings \ mpilgrim. In the second round, k gets the second key word OS, and v gets the corresponding value Windows_NT.
(3) using multi-variable assignment and list parsing, you can use a single row statement to replace the entire for loop. In actual encoding, it is just a matter of personal style. I like it because it maps a dictionary to a list and then combines the list into a string, this process is clear. Other programmers prefer to write it into a for loop. Note that the output is the same in both cases, but this version is a little faster, because it only has one print statement instead of many.

Now let's take a look at the for loop of MP3FileInfo in the sample program fileinfo. py described in Chapter 5th.

Copy codeThe Code is as follows:
TagDataMap = {"title": (3, 33, stripnulls ),
"Artist": (33, 63, stripnulls ),
"Album": (63, 93, stripnulls ),
"Year": (93, 97, stripnulls ),
"Comment": (97,126, stripnulls ),
"Genre": (127,128, ord)} (1)
.
.
.
If tagdata [: 3] = "TAG ":
For tag, (start, end, parseFunc) in self. tagDataMap. items (): (2)
Self [tag] = parseFunc (tagdata [start: end]) (3)

(1) tagDataMap is a class attribute that defines the tag we are searching for in an MP3 file. Mark storage as a fixed-length field. As long as we read the last 128 bytes of the file, 3rd to 32 bytes will always be the name of the song, and 33-62 will always be the name of the singer, 63-92 is the album name, and so on. Note that tagDataMap is a tuple dictionary. each tuple contains two integers and a function reference.
(2) This seems complicated, but it is not. The for Variable Structure here matches the structure of the list elements returned by items. Remember, items returns a list of tuple in the form of (key, value. The first element of the list is ("title", (3, 33, <function stripnulls>), so in the first round of the loop, the tag is "title", and the start is 3, end is 33, and parseFunc is the stripnulls function.
(3) Now we have extracted all the parameters from a single MP3 tag, which makes it easy to save the tag data. We split the tagdata from start to end to obtain the actual data of the tag, call parseFunc for subsequent processing of the data, and then
The return value of parseFunc is assigned to the key tag in the pseudo dictionary self. After traversing all the elements in tagDataMap, self has all the Marked Values and you know what it looks like.

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.