With old Ziko Python's little trick about loops

Source: Internet
Author: User
Tags iterable
Not to say that while is not necessary, such as the previous list of the guessing number game, in business logic, with while is easier to understand (of course, is limited to the business needs of the game). In addition, in some cases, for is not simply to iterate over the elements of an object, such as having a requirement to take one from another, and so on.

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

Range

In the big list (4), the range () is specifically described in this built-in function, and crossing can go back to that tutorial to review it. The point here is to review and display its for loop as a counter to use.

Remember that there was a problem with the Tutorial: List the number that is divisible by 3 within 100. The following references the code of the problem and the result of the operation.

The 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 Run Result:

The 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 question, if rewrite (also have netizens in the blog proposed rewriting method)

The code is 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, 87, 90, 93, 96, 99]

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

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

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

The 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 , 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, it is mainly to let crossing understand the function of range () counter in the For loop.

Zip

In "Unimaginable for", zip has been introduced, here also to mention this function, not only to review, but also to drill down, but mainly it will often be used in the loop.

Zip is a function for parallel traversal.

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

The 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, in the previous lecture there is a more perfect code, please crossing appreciate.

Zip to complete the above task, is to do this:

The 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 in the List1 and List2 two objects into a tuple (a, B) and then manipulate the two elements.

The 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, crossing can be understood as, the two list is compressed into a (Zip) a list, but could not find the pairing is lost.

Can be compressed, can also be decompressed, in the following way is the reverse.

The 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)]

Yours faithfully note that the decompression results, compared to the previous compression results, the second item is less than one element 19, because when the compression is lost.

It doesn't seem to have anything to do with for. 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 "}

There are several solutions, if you use a For loop, you can do this (of course, crossing if there is a method, please post it).

The 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 out:

The code is 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 also be used this way. Yes, that's essentially what happened. If the above line is broken apart, crossing will understand the mystery.

The code is 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 () function to convert the above list to dictionary
{' Python ': ' Lang ', ' Qiwsir.github.io ': ' Site ', ' qiwsir ': ' Name '}

At this point, do you understand the relationship between the zip () and the loop? With it you can make some loops simpler. In particular, when reading a database with Python (such as MySQL), the function of Zip () is more apparent.

Enumerate

Enumerate's detailed explanation, in the "deeper point, more understand list" has been explained, here to review.

What if you want to get a list of offsets (that is, the foot tag) and the corresponding elements for each of these elements? Can do this:

The 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 function of enumerate is to simplify the above operations:

The code is as follows:


>>> Enumerate (mylist)
#出现这个结果, you can display content with a list. Similar will appear in the later course, which means that the iteration is possible.
>>> List (Enumerate (mylist))
[(0, ' Qiwsir '), (1, 703), (2, ' Python ')]

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

The code is as follows:


Class Enumerate (object)
| Enumerate (iterable[, start]), iterator for index, value of iterable
|
| Return an Enumerate object. Iterable must is another object that supports
| Iteration. The enumerate object yields pairs containing a count (from
| Start, which defaults to zero) and a value of 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 friends may seem a little confused, it doesn't matter, at least Browse, see a ballpark. Because as individuals practice more and more, the understanding of the meaning of the document will become more and more profound. This is like to make Fox rushed, just learned a lone nine sword of formulas and moves, understanding is not very deep, only in the practice of continuous killing, especially with the east, such as the Invincible Master, can more and more realize the mystery of the Nine swords alone.

  • Related Article

    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.