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 so many other ways that you don't usually need them.
Most other languages do not have a powerful list data type like Python, so you need to do many things yourself, specifying the start, end, and stride length to define a range of integers or characters or other repeatable entities. In Python, however, a for loop simply loops on a list and works the same way as list parsing.
1. For loop Introduction
Copy the Code code 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 for the For loop is similar to the list parsing. Li is a list, and S will receive the value of each element sequentially, starting with the first element.
(2) A For loop can contain any number of lines of code, such as an if statement or any other indented block.
(3) That's why you've never seen A For loop before: we don't need it yet. It's amazing how often you need a for loop in other languages when all you want is a join or list parsing.
It is also very easy to make a "normal" (Visual Basic Standard) count for loop.
2. Simple counting
Copy the Code code 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 an integer list that controls the loop. I know it looks strange, but it can be useful to count loops occasionally (I just say occasional).
(2) We've never used this before. This is the thinking style of Visual Basic. get rid of it. The correct way to traverse the list is shown in the previous example.
The For loop is not just for simple counting. They can traverse any type of thing. The following example is an example of traversing a dictionary with a for loop.
3. Traverse Dictionary
Copy the Code code as follows:
>>> Import OS
>>> for K, V in Os.environ.items (): (1) (2)
... print "%s=%s"% (k, v)
Userprofile=c:\documents and Settings\mpilgrim
Os=windows_nt
Computername=mpilgrim
Username=mpilgrim
[... Slightly ...]
>>> print "\ n". Join (["%s=%s"% (k, v)
... for K, V in Os.environ.items ()]) (3)
Userprofile=c:\documents and Settings\mpilgrim
Os=windows_nt
Computername=mpilgrim
Username=mpilgrim
[... Slightly ...]
(1) Os.environ is the dictionary of the Environment variables defined on your system. Under Windows, these variables are user and system variables that can be accessed from MS-DOS. Under UNIX, they are the exported (output) variables in your shell startup script. In Mac OS, there is no concept of environment variables, so this dictionary is empty.
(2) Os.environ.items () returns a tuple of list:[(Key1, value1), (Key2, value2), ...]. The For loop iterates through the list. In the first round, it assigns key1 to K, value1 to V, so k = Userprofile,v = C:\Documents and Settings\mpilgrim. In the second round, K gets the second key word os,v to get the corresponding value WINDOWS_NT.
(3) With multivariate assignment and list parsing, you can replace the entire for loop with a single-line statement. Whether this is done in the actual coding is only a matter of personal style; I like it because it is clear that a dictionary is mapped to a list and then the list is merged into a single string. Other programmers prefer to write it as a for loop. Note that in both cases the output is the same, but this version is slightly faster because it has only one print statement instead of many.
Now let's take a look at the mp3fileinfo for loop in the sample program fileinfo.py introduced in the 5th chapter.
Copy the Code code as follows:
Tagdatamap = {"title": (3, Stripnulls),
"Artist": (Stripnulls),
"Album": (Stripnulls,,,),
"Year": (Stripnulls),
"Comment": (126, Stripnulls),
"Genre": (127, +, 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 property that defines the tags we are searching for in a MP3 file. The tag is stored as a fixed length field, as long as we read the last 128 bytes of the file, then the 3rd to 32nd byte is always the name of the song, 33-62 is always the name of the singer, 63-92 is the name of the album, and so on. Note that Tagdatamap is a tuple of dictionary, each tuple contains two integers and a function reference.
(2) This looks more complicated, but it is not. The for variable structure here matches the structure of the elements of the list returned by items. Remember, items returns a list of a tuple of the form (key, value). List the first element is ("title", (3, X, )), so the first round of the loop, tag is "title", Start is 3,end for 33,parsefunc function Stripnulls.
(3) Now that we've extracted all the parameters from a single MP3 tag, it's easy to save the tag data. We shard the tagdata from start to end to get the actual data for this tag, call Parsefunc to perform subsequent processing of the data, and then
The return value of the Parsefunc is assigned as a value to the key tag in the pseudo-dictionary self. After iterating through all the elements in Tagdatamap, self has all the tagged values, and you know what it looks like.