With old Ziko Python's little trick about cycling _python

Source: Internet
Author: User
Tags iterable in python

It's not that while, like the previous list of guessing numbers, it's easier to understand in business logic (which is limited to the business needs of that game). In addition, in some cases, for is not simply to traverse the elements of an object, such as having a separate request, and so on.

In the practice of writing code, some other functions need to be used to deal with some of the requirements in the loop, such as the range described earlier is a good thing to be seen as a counter in the loop.

Range

In the reader list (4), the built-in function of range () is described in detail, and the tutorial can go back to that section for a review. The key here is to review and show it for The loop, as a counter used.

Remember that there was a problem in the Tutorial: List the numbers divisible by 3 within 100. The following refers to the code and run results for that problem.

Copy Code code 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 Run Results:

Copy Code code 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, 96, 99]

This question, if rewritten (also has the netizen to propose the rewriting method in the blog)

Copy Code code as follows:

>>> aliquot = [x for x in range (1,100) if x%3==0] #用list解析, essentially not much different from 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, 96, 99]

>>> aliquot = Range (3,100,3) #这种方法更简单. This is a blog of a netizen to provide.
>>> 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, 96, 99]

If you have a string of letters, just want to separate one letter from the string. This can be done, which is an important use of range ().

Copy Code code 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 interval of an example can be arbitrarily specified. Or the previous question, you can also select all the numbers that can be divisible by 3 in the following way.

Copy Code code 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 , 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, 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 , 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, 96, 99]

Through the above example, it is important to let reader understand the effect of range () on the counter in the For loop.

Zip

In "Unimaginable for", the zip has been introduced, here also mention this function, not only review, but also in-depth, but also the main is that it will often be used in the loop.

A zip is a function that is used for parallel traversal.

For example, there are two lists, and elements are made up of integers, if the corresponding position elements are computed. One way to do this is to take the elements out of the two list and sum them up by looping.

Copy Code code 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 in the last lecture there is a more perfect code, please reader appreciate.

Zip to complete the above task, this is done:

Copy Code code 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 place the corresponding elements in the List1 and List2 two objects into a tuple (a,b), and then manipulate the two elements.

Copy Code code 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, reader can be understood to be two list compressed into a (Zip) a list, but could not find a pair of lost.

Can compress, also can decompress, in the following way is the reverse.

Copy Code code 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)]

Note that the results of the decompression, compared to the previous compression results, the second item is less than one element 19, because the compression is lost.

It doesn't seem to have anything to do with for a. 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"}, transform this dictionary into: infor = {"Qiwsir ': ' Name ', ' Qiwsir.github.io ': ' site ', ' python ': ' Lang '}

The solution has several, if use for loop, can do this (of course, reader if there is a method, welcome to paste out).

Copy Code code as follows:

>>> infor = {}
>>> for K,v in Myinfor.items ():
... infor[v]=k
...
>>> infor
{' Python ': ' Lang ', ' Qiwsir.github.io ': ' Site ', ' qiwsir ': ' Name '}

Try the following with Zip ():

Copy Code code as follows:

>>> dict (Zip (myinfor.values (), Myinfor.keys ())
{' Python ': ' Lang ', ' Qiwsir.github.io ': ' Site ', ' qiwsir ': ' Name '}

Alas, what is the situation? The original zip () can be used in this way. Yes, that's essentially what happened. If the above line is broken apart, reader will understand the mystery.

Copy Code code as follows:

>>> myinfor.values () #得到两个list
[' Python ', ' qiwsir ', ' Qiwsir.github.io ']
>>> Myinfor.keys ()
[' Lang ', ' name ', ' site ']
>>> temp = Zip (Myinfor.values (), Myinfor.keys ()) #压缩成一个list, each element is a tuple
>>> Temp
[' Python ', ' Lang '], (' Qiwsir ', ' name '), (' Qiwsir.github.io ', ' site ')]

>>> dict (temp) #这是函数dict () to convert the above list to dictionary
{' Python ': ' Lang ', ' Qiwsir.github.io ': ' Site ', ' qiwsir ': ' Name '}

So, do you understand the relationship between zip () and loop? It allows some loops to be simplified. Especially when reading a database in Python (such as MySQL), zip () is more likely to appear.

Enumerate

Enumerate detailed explanation, in "further deeper, better understand list" has been explained, here to review.

What if you want to get a list of each element's offsets (that is, that pin) and corresponding elements? You can do this:

Copy Code code 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 Code code as follows:

>>> Enumerate (mylist)
<enumerate object at 0xb74a63c4> #出现这个结果, can display content with list. Similar will appear in the following course, meaning that it can be iterated.
>>> List (Enumerate (mylist))
[(0, ' Qiwsir '), (1, 703), (2, ' Python ')]

A deep exposition of enumerate () also depends on this official document:

Copy Code code 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 to 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 friends may look a little confused, it doesn't matter, at least browse, look at a ballpark. Because as individuals practice more and more, the meaning of the document will be more and more profound understanding. This is like the Fox Chong, just learned the formula and the sword of solitary nine swords, understanding is not very profound, only in the continuous fight and kill practice, especially with the East Invincible and other masters, can more and more realize the mystery of solitary nine swords.

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.