For loop in Python

  • 2020-04-02 13:22:52
  • OfStack

Python, like most other languages, has a for loop. The only reason you haven't seen them yet is that Python is so good at so many other things that you don't usually need them.

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

1. The for   Circulation is introduced


>>> 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 that for list parsing. Li is a list, and s will receive the values of each element in turn, starting with the first element.
(2)   Like if statements or other arbitrary indentation blocks, a for loop can contain any number of lines of code.
(3)   This is why you haven't seen the for loop before: we don't need it yet. It's amazing how often you use a for loop in other languages when all you want is a join or list resolution.

It's also easy to do a "normal" (Visual Basic standard) count for loop.

2. Simple counting


>>> 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 through which to control the loop. I know it looks a little strange, but it's useful for counting loops occasionally (and I'm just saying occasionally).
(2)   We've never used it that way. This is the Visual Basic style of thinking. 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 iterate over any type of thing. The following example is an example of using a for loop to traverse a dictionary.

3. The traverse   The dictionary


>>> import os
>>> for k, v in os.environ.items():      (1) (2)
...     print "%s=%s" % (k, v)
USERPROFILE=C:Documents and Settingsmpilgrim
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 Settingsmpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim
[... slightly ...]

(1)   Os.environ is the dictionary of environment variables defined on your system. Under Windows, these variables are user and system variables that can be accessed from ms-dos. On UNIX, they are the variables that export in your shell startup script. In Mac OS, there is no concept of an environment variable, so the dictionary is empty.
(2)   Os.envion.items () returns a list of tuples: [(key1, value1), (key2, value2),...] . The for loop iterates over the list. In the first round, it assigns key1 to k and value1 to v, so k = USERPROFILE, v = C:\Documents and Settings\mpilgrim. In the second round, k gets the second key word OS, and v gets the corresponding value Windows_NT.
(3)   Using multivariable assignments and list resolution, you can replace the entire for loop with a single line statement. Whether to do this in actual coding is just a matter of personal style; I like it because it's so clear to map a dictionary to a list and then merge 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, however this version is slightly faster because it has only one print statement instead of many.

Now let's look at the for loop for MP3FileInfo in the sample program fileinfo.py introduced in chapter 5.


    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. The markup is stored as a fixed-length field, and as long as we read out the last 128 bytes of the file, bytes 3 to 32 are always the name of the song, 33-62 are always the name of the singer, 63-92 are the name of the album, and so on. Note that the tagDataMap is a dictionary of tuples, each of which contains two integers and a function reference.
(2)   This one looks a little more complicated, but it's not. The for variable structure here matches the structure of the elements of the list returned by items. Remember, items return a list of tuples in the form of (key, value). The first element of list is ("title", (3, 33, < The function stripnulls > ), so in the first round of the loop, tag is "title", start is 3, end is 33, and parseFunc is the 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 slice the tagdata from start to end to get the actual data for this tag, call parseFunc to do the following processing of the data, and then
The return value of parseFunc is assigned as a value to the key tag in the pseudo-dictionary self. After traversing all the elements in tagDataMap, self has the values of all the tags, and you know what it looks like.


Related articles: