Learn the Python for loop from the old one

  • 2020-04-02 14:12:11
  • OfStack

Cut the crap and get to work.

The basic operation of for

A for is a loop that reads the elements in turn from an object. Take a look at the following example, and loop through the data objects you've already learned to see what works and what doesn't. It's also a review of the past.


>>> name_str = "qiwsir"
>>> for i in name_str:  # Can be str use for cycle
...     print i,
...                    
q i w s i r >>> name_list = list(name_str)
>>> name_list
['q', 'i', 'w', 's', 'i', 'r']
>>> for i in name_list:     # right list Can also be used
...     print i,
...
q i w s i r >>> name_set = set(name_str)    #set You can also use
>>> name_set
set(['q', 'i', 's', 'r', 'w'])
>>> for i in name_set:
...     print i,
...
q i s r w >>> name_tuple = tuple(name_str)
>>> name_tuple
('q', 'i', 'w', 's', 'i', 'r')
>>> for i in name_tuple:        #tuple Can also!
...     print i,
...
q i w s i r >>> name_dict={"name":"qiwsir","lang":"python","website":"qiwsir.github.io"}
>>> for i in name_dict:             #dict There is no exception
...     print i,"-->",name_dict[i]
...
lang --> python
website --> qiwsir.github.io
name --> qiwsir

In addition to the data types above, you can also use for files, which is covered in the previous two articles, no red header files, on how to use for to read file objects. If you forget, you can browse.

For in the list analysis, the use can not be underestimated, this in the explanation of the list analysis, has already explained, but it is better to review again, the so-called study and often review it, not also ha ha ha.


>>> one = range(1,9)        
>>> one
[1, 2, 3, 4, 5, 6, 7, 8]
>>> [ x for x in one if x%2==0 ]
[2, 4, 6, 8]

What also said, list analysis of the tough, in the future learning will be more and more experience, admire it.

If you use python3 as a column bit, you'll find dictionary parsing and tuple parsing to be wonderful.

To go up a notch, you have to generalize. To summarize the "for" loop, here is the following:

Please enter a picture description

In one word:


for iterating_var in sequence:
    statements

Iterating_var is the iteration variable of the object sequence, that is, the sequence must be an object that can have a certain sequence, especially without a certain sequence, that is, the elements can be obtained according to a certain script. Of course, the file object belongs to the sequence, so we don't use a footer to get each line, but if we read it out, because it's also a STR, we can still use a footer to read its contents.

zip

What is zip? In interactive mode with help(zip), the official document is:

Zip (...).
Zip (seq1 [, seq2 [...]) - > [(seq1 [0], seq2 [0]...), (...)"
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
Experiment to understand the document above:


>>> a = "qiwsir"
>>> b = "github"
>>> zip(a,b)
[('q', 'g'), ('i', 'i'), ('w', 't'), ('s', 'h'), ('i', 'u'), ('r', 'b')]
>>> c = [1,2,3]
>>> d = [9,8,7,6]
>>> zip(c,d)
[(1, 9), (2, 8), (3, 7)]
>>> e = (1,2,3)
>>> f = (9,8)
>>> zip(e,f)
[(1, 9), (2, 8)] >>> m = {"name","lang"} 
>>> n = {"qiwsir","python"}
>>> zip(m,n)
[('lang', 'python'), ('name', 'qiwsir')]
>>> s = {"name":"qiwsir"}
>>> t = {"lang":"python"}
>>> zip(s,t)
[('name', 'lang')]

Zip is a built-in function whose arguments must be of some sort of sequence data type, and in the case of a dictionary, the key is treated as a sequence. Then the corresponding elements of the sequence are formed into tuples in turn, which are regarded as the elements of a list.

The following is a special case, when the parameter is a sequence of data, the generated result looks like:


>>> a 
'qiwsir'
>>> c 
[1, 2, 3]
>>> zip(c)
[(1,), (2,), (3,)]
>>> zip(a)
[('q',), ('i',), ('w',), ('s',), ('i',), ('r',)]

This function is used with "for" to implement:


>>> c
[1, 2, 3]
>>> d
[9, 8, 7, 6]
>>> for x,y in zip(c,d):    # One to one printing
...     print x,y
...
1 9
2 8
3 7
>>> for x,y in zip(c,d):    # The two list The corresponding quantities in.
...     print x+y
...
10
10
10

If you don't use zip, you can also write:


>>> length = len(c) if len(c)<len(d) else len(d)    # judge c,d The length of, let's take the short length out
>>> for i in range(length):
...     print c[i]+d[i]
...
10
10
10

Which is better? The former? The latter? Ha ha. I think so. Here's another way:


>>> [ x+y for x,y in zip(c,d) ]
[10, 10, 10]

As I said many times before, list parsing is tough. Of course, you can also:


>>> [ c[i]+d[i] for i in range(length) ]
[10, 10, 10]

I'm going to use the for loop a lot later, but I've already used it a lot. So, the officer should not feel too strange.


Related articles: