Gimmicks about loops
Loops, whether initiated by while or for, are often used in Python programming. For, in particular, is generally believed to be faster than while, and it is also easier to write (this may vary from person to person, but it is true that the execution time is fast). Therefore, in practice, for is used more often than while is not used. For example, in the number guessing game listed above, in business logic, While is much easier to understand (limited, of course, to the business needs of that game). In addition, in some cases, for does not simply iterate over the elements of an object, such as the requirement to take one from another, and so on.
In practice, in order to deal with the requirements of a loop, you need to use other functions, such as range, which is a good thing to think of as a counter in a loop.
range
Specifically, show the range() built-in function as a counter in its for loop.
Remember there was a problem in the tutorial: [list the numbers divisible by 3 within 100] the code and results of that problem are quoted below.
#! /usr/bin/env python #coding: utF-8 aliquot = [] for n in range(1,100): if n%3 == 0: aliquot. Append (n) print aliquotCopy the code
Code running results:
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]Copy the code
So let me rewrite this problem
>>> aliquot = [x for x in range(1,100) if x%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, >>> aliquot = range(3,100,3) # this method is simpler. This is provided by a netizen on 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]Copy the code
If you have a string of letters, you want to take only one letter from the string. You can do this, which is an important use of range().
>>> one = "Ilikepython"
>>> new_list = [ one[i] for i in range(0,len(one),2) ]
>>> new_list
['I', 'i', 'e', 'y', 'h', 'n']
Copy the code
Of course, the examples of intervals can be arbitrarily specified. Once again, we can pick all the numbers that are divisible by 3 by the following way.
>>> 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]
Copy the code
zip
Introduce ZIP, which is often used in loops as well.
Zip is a function for parallel traversal.
Let’s say I have two lists, and the elements are integers, and if I take the sum of the elements. One way to do this is through a loop, taking elements from each list and summing them up.
> > > 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]Copy the code
Zip completes the above tasks by:
>>> list1 [2, 4, 6, 8] >>> list2 [11, 13, 15, 17, 19] >>> for a,b in zip(list1,list2): ... print a+b, ... 13 17 and 25Copy the code
Zip () puts the corresponding elements of list1 and list2 into a tuple (a,b), and operates on both elements.
>>> list1
[2, 4, 6, 8]
>>> list2
[11, 13, 15, 17, 19]
>>> zip(list1,list2)
[(2, 11), (4, 13), (6, 15), (8, 17)]
Copy the code
For this function, you can compress two lists into a (zip) list, but if you can’t find a match, you throw it away.
It can compress, it can uncompress, it’s the other way around.
>>> result = zip(list1,list2)
>>> result
[(2, 11), (4, 13), (6, 15), (8, 17)]
>>> zip(*result)
[(2, 4, 6, 8), (11, 13, 15, 17)]
Copy the code
Notice that the result of the decompression, compared to the result before the compression, there is one element 19 missing from the second term, because it was lost in the compression.
That doesn’t seem to have anything to do with for. Take your time, think of a problem and see how to solve it:
Myinfor = {“name”:”hiekay”,”site”:”hiekay.github. IO “,”lang”:”python”} infor = {“hiekay”:”name”,”hiekay.github.io”:”site”,”python”:”lang”}
There are a couple of ways to do it, but if you do a for loop, you can do this.
>>> infor = {}
>>> for k,v in myinfor.items():
... infor[v]=k
...
>>> infor
{'python': 'lang', 'hiekay.github.io': 'site', 'hiekay': 'name'}
Copy the code
Try using zip() :
>>> dict(zip(myinfor.values(),myinfor.keys()))
{'python': 'lang', 'hiekay.github.io': 'site', 'hiekay': 'name'}
Copy the code
It turns out zip() still works like this. Yes, that’s essentially what happened. If you break down the top row, you’ll see why.
>>> myinfor.values() # get two list ['python', 'hiekay', 'hiekay.github. IO '] >>> myinfor.keys() ['lang', 'name', >>> temp = zip(myinfor.values(),myinfor.keys()) Each element is a tuple > > > \ [(" python ", "lang"), (' hiekay ', 'name'), (' hiekay. Making. IO, 'site')] >>> dict(temp) # Dict () converts the above list to dictionary {'python': 'lang', 'hiekay.github. IO ': 'site', 'hiekay': 'name'}Copy the code
Now, do you understand the relationship between zip() and loops? It simplifies some loops. Zip () is especially useful when reading from a database in Python, such as mysql.
enumerate
What if you want to evaluate a list and want the offset of each element (that is, the pin) and the corresponding element? It can go like this:
>>> mylist = ["hiekay",703,"python"]
>>> new_list = []
>>> for i in range(len(mylist)):
... new_list.append((i,mylist[i]))
...
>>> new_list
[(0, 'hiekay'), (1, 703), (2, 'python')]
Copy the code
The enumerate() function is used to combine an iterable data object (such as a list, tuple, or string) into an index sequence that lists both data and data subscripts, typically used in a for loop.
>>> enumerate(mylist) <enumerate object at 0xb74a63C4 > Something like this will come up later in the course, which means iterable. >>> list(enumerate(mylist)) [(0, 'hiekay'), (1, 703), (2, 'python')]Copy the code