Python for Loop detailed _python

Source: Internet
Author: User

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

Most other languages don't have a strong list data type like Python, so you need to do a lot of things yourself, specifying start, end, and step lengths to define a range of integers or characters or other repeatable entities. But in Python, the for loop simply loops over a list and works the same way as list parsing.

1. For loop Introduction

Copy 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 list resolution. Li is a list, and S will receive the value of each element in turn, starting with the first element.
(2) Like an if statement or any other indented block, the For loop can contain any number of lines of code.
(3) This is why you haven't seen a for loop before: we don't need it so far. It's amazing that when you want a join or list resolution, it's often necessary to use a For loop in other languages.

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

2. Simple counting

Copy 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) The range generates a list of integers through which to control the loop. I know it looks a little strange, but it's useful for counting loops occasionally (I just say occasionally).
(2) We've never used it that way. 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 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
[... A little ...]
>>> 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
[... A little ...]

(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 variables that are exported (output) in your shell startup script. In Mac OS, there is no concept of an environment variable, so this dictionary is empty.
(2) Os.environ.items () returns a tuple 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. The second round, K gets the second key word os,v get the corresponding value WINDOWS_NT.
(3) Using multivariable Assignment and list parsing, you can use Single-line statements to replace the entire for loop. Whether this is done in the actual coding is just a matter of personal style; I like it because it's clear that mapping a dictionary to a list and then merging the list into a string. Other programmers prefer to write it as a for loop. Note that the output is the same in both cases, but this version is slightly faster because it has only one print statement rather than many.

Now let's take a look at the mp3fileinfo for loop in the sample program fileinfo.py in chapter 5th.

Copy Code code as follows:

Tagdatamap = {"title": (3, Stripnulls),
"Artist": (Stripnulls,),
"Album": (Stripnulls),
"Year": (Mr, Stripnulls,
"Comment": (126, Stripnulls),
"Genre": (127, 128, ORD)} (1)
.
.
.
If tagdata[:3] = = "TAG":
For tags, (start, End, Parsefunc) in Self.tagDataMap.items (): (2)
Self[tag] = Parsefunc (Tagdata[start:end]) (3)

(1) Tagdatamap is a class attribute that defines the tags we are searching for in a MP3 file. tag is stored as a fixed-length field, as long as we read out 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 singer's name, 63-92 is the album's name, and so on. Note that Tagdatamap is a tuple dictionary, each tuple contains two integers and a function reference.
(2) This looks more complicated, but it's not. The for variable structure here matches the structure of the elements of the list returned by the items. Remember, items return a list of tuple (key, value). The first element of the list is ("title", (3, <function stripnulls>)), so the first round of the loop, tag is "title", and start is 3,end for 33,parsefunc function STRIPN Ulls.
(3) Now that we've extracted all the parameters from a single MP3 tag, it's easy to save the tag data. We fragment the Tagdata from start to end to get the actual data of the tag, call Parsefunc to process the data, and then
The Parsefunc return value is assigned to the keyword tag in the pseudo dictionary self as a value. After iterating through all the elements in Tagdatamap, self has all the tagged 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.