I learned Python tricks about loops and python tricks
It is not to say that while is not used. For example, the number game that is listed above is easier to understand in terms of business logic (of course, it is limited to the business needs of that game ). In addition, in some cases, for does not simply traverse the elements in the object, for example, there is a requirement to take one by one.
In the practice of writing code, some other functions are required to deal with certain requirements in the loop. For example, the range mentioned above is a good thing to be seen as a counter in the loop.
Range
In "a large list (4)", I made a detailed introduction to the built-in function range (). You can go back to the tutorial to review it. Here we will focus on reviewing and presenting its for loop as a counter.
I still remember that there was a problem in the Tutorial: listing the number of 3 divisible by less than 100. The code and running result of the problem are referenced below.
Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8
Aliquot = []
For n in range (1,100 ):
If n % 3 = 0:
Aliquot. append (n)
Print aliquot
Code running result:
Copy codeThe Code is as follows:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
This problem can be rewritten. (Some netizens have proposed the rewrite method in their blogs)
Copy codeThe Code is as follows:
>>> Aliquot = [x for x in range (1,100) if x % 3 = 0] # Use list resolution, which is essentially similar to the above
>>> Aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>> Aliquot = range (3,100, 3) # This method is simpler. This is provided by a netizen in the blog.
>>> Aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
If there is a string consisting of letters, you only want to extract one letter from the string. This is an important use of range.
Copy codeThe Code is as follows:
>>> One = "Ilikepython"
>>> New_list = [one [I] for I in range (0, len (one), 2)]
>>> New_list
['I', 'I', 'E', 'y', 'h', 'n']
Of course, the example of interval can be specified at will. We can also use the following method to select all the numbers that can be divisible by three.
Copy codeThe Code is as follows:
>>> All_int = range (1,100)
>>> All_int
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> Aliquot = [all_int [I] for I in range (len (all_int) if all_int [I] % 3 = 0]
>>> Aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
Through the above example, the viewer can understand the function of range () in the for loop.
Zip
In "unimaginable for", we have already introduced zip. Here we also need to mention this function, not only for review, but also for further exploration, more importantly, it is often used in loops.
Zip is a function used for parallel traversal.
For example, there are two lists whose elements are composed of integers. If the sum of the corresponding position elements is calculated. One way is to retrieve elements from two lists through a loop, and then sum them.
Copy codeThe Code is as follows:
>>> List1 = range (2, 10, 2)
>>> List1
[2, 4, 6, 8]
>>> List2 = range (11,20, 2)
>>> List2
[11, 13, 15, 17, 19]
>>> Result = [list1 [I] + list2 [I] for I in range (len (list1)]
>>> Result
[13, 17, 21, 25]
As described in the for loop statement, the above method is not perfect, and there is a perfect code in the previous lecture. Please take a look at it.
Zip is used to complete the preceding task:
Copy codeThe Code is as follows:
>>> List1
[2, 4, 6, 8]
>>> List2
[11, 13, 15, 17, 19]
>>> For a, B in zip (list1, list2 ):
... Print a + B,
...
13 17 21 25
The function of zip () is to put the corresponding elements of the list1 and list2 objects into a tuples (a, B), and then operate on the two elements.
Copy codeThe Code is as follows:
>>> List1
[2, 4, 6, 8]
>>> List2
[11, 13, 15, 17, 19]
>>> Zip (list1, list2)
[(2, 11), (4, 13), (6, 15), (8, 17)]
For this function, the reader can understand that two lists are compressed into a list (zip), but the matching is lost if no matching is found.
It can be compressed or decompressed. The following method is the opposite.
Copy codeThe Code is as follows:
>>> Result = zip (list1, list2)
>>> Result
[(2, 11), (4, 13), (6, 15), (8, 17)]
>>> Zip (* result)
[(2, 4, 6, 8), (11, 13, 15, 17)]
Observe the column bit. the result obtained by decompression is equal to the result before compression. The second item has 19 fewer elements, because it is lost during compression.
This seems to have nothing to do with. Don't worry. Think about a problem and see how to solve it:
Problem description: There is a dictionary, myinfor = {"name": "qiwsir", "site": "qiwsir. github. io "," lang ":" python "}, convert this dictionary to: infor = {" qiwsir ":" name "," qiwsir. github. io ":" site "," python ":" lang "}
There are several solutions. If you use a for loop, you can do this (of course, if you have a method, post it ).
Copy codeThe Code is as follows:
>>> Infor = {}
>>> For k, v in myinfor. items ():
... Infor [v] = k
...
>>> Infor
{'Python': 'lang ', 'qiwsir. github. io': 'SITE', 'qiwsir ': 'name '}
Use zip () below to try it:
Copy codeThe Code is as follows:
>>> Dict (zip (myinfor. values (), myinfor. keys ()))
{'Python': 'lang ', 'qiwsir. github. io': 'SITE', 'qiwsir ': 'name '}
Why? It turns out that this zip () can be used in this way. Yes. This is essentially the case. If we break down the line above, we will understand the mysteries of the line.
Copy codeThe Code is as follows:
>>> Myinfor. values () # obtain two lists.
['Python', 'qiwsir ', 'qiwsir. github. io']
>>> Myinfor. keys ()
['Lang ', 'name', 'SITE']
>>> Temp = zip (myinfor. values (), myinfor. keys () # compress into a list. Each element is a tuple.
>>> Temp
[('Python', 'lang '), ('qiwsir', 'name'), ('qiwsir. github. io ', 'SITE')]
>>> Dict (temp) # this function is used by dict () to convert the above list to a dictionary
{'Python': 'lang ', 'qiwsir. github. io': 'SITE', 'qiwsir ': 'name '}
So far, do you understand the relationship between zip () and loop? With this function, some loops can be simplified. Especially when reading a database using python (such as mysql), zip () is more effective.
Enumerate
The detailed explanation of enumerate has been explained in "more in-depth, more understanding list". Let's review it here.
What should I do if I want to get the offset (that is, the script) of each element and the corresponding element from a list? You can do this:
Copy codeThe Code is as follows:
>>> Mylist = ["qiwsir", 703, "python"]
>>> New_list = []
>>> For I in range (len (mylist )):
... New_list.append (I, mylist [I])
...
>>> New_list
[(0, 'qiwsir '), (1,703), (2, 'python')]
The role of enumerate is to simplify the above operations:
Copy codeThe Code is as follows:
>>> Enumerate (mylist)
<Enumerate object at 0xb74a63c4> # When this result is displayed, you can use list to display the content. Similar content will appear in subsequent courses, which means it can be iterated.
>>> List (enumerate (mylist ))
[(0, 'qiwsir '), (1,703), (2, 'python')]
For more information about enumerate (), see this official document:
Copy codeThe Code is as follows:
Class enumerate (object)
| Enumerate (iterable [, start])-> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| Iteration. The enumerate object yields pairs containing a count (from
| Start, which defaults to zero) and a value yielded by the iterable argument.
| Enumerate is useful for obtaining an indexed list:
| (0, seq [0]), (1, seq [1]), (2, seq [2]),...
|
| Methods defined here:
|
| Getattribute (...)
| X. getattribute ('name') <=> x. name
|
| Iter (...)
| X. iter () <=> iter (x)
|
| Next (...)
| X. next ()-> the next value, or raise StopIteration
Data and other attributes defined here:
New =
T. new (S,...)-> a new object with type S, a subtype of T
For official documents, some may look a little confused. It doesn't matter. at least check it out and check it out. As personal practices increase, the meaning of documents will become more and more profound. This is like Ling huchong. after learning the skills and Tactics of his unique sword, he does not have a profound understanding. Only after the continuous practices of the fight and killing, especially the undefeated experts in the east, in order to learn more and more about the secrets of the lone sword.