Python Basics--08 Iterations & List Generation

Source: Internet
Author: User

1. Iteration 1.1 Features

In Python, an iteration is done through a for ... in.

Python's for loop can be used not only on a list or a tuple, but also on any other object that can iterate

A For loop can work on an iterative object far more than List,tuple,str,unicode,dict, and if an object says it can iterate, then we iterate it directly with a for loop .

The iterative operation is for a collection, regardless of whether the collection is ordered or unordered, we can always use the for loop to sequentially remove each element of the collection

1.2 Iteration Objects

A collection is a data structure that contains a set of elements that we have covered:

ordered set : List,tuple,str and Unicode;

Unordered collection : Set

unordered collection and has Key-value Yes : dict

1.3 Index iterations

In 1.3.1Python, iterations are always taken out of the element itself, not the index of the element

1.3.2 using the Enumerate () function , we can simultaneously bind indexes index and element name in the For Loop.

1.3.3enumerate () function put: [' Adam ', ' Lisa ', ' Bart ', ' Paul ']

became similar: [(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]

Therefore,each element of the enumerate () iteration is actually a tuple

1.3.4 Example

>>> l=[' Adam ', ' Lisa ', ' Bart ', ' Paul '

>>> for Index,name in Enumerate (L):

... print index, '-', name

...

0-adam

1-lisa

2-bart

3-paul

2. List-Generated

[x * x for x in range (1, one)] <==> [variable arithmetic expression for variable in iterator]

[x * x for x in range (1, one) if x% 2 = 0] <==> [variable arithmetic expression for variable in iterator if filter condition]

[M + N for m in ' ABC ' for n in ' 123 '] <==> [multivariable arithmetic expression for variable 1 in iterator 1 for variable 2 in iterator 2]

[X*y for x, y in Zip (range (1,100,2), Range (2,100,2))] <==> [multivariable arithmetic expression for variable 1, variable 2,... in iterator ( iterator element is tuple )]

[Generate_tr (Name,score) for name, score in D.iteritems ()] <==> [ multivariate function to make arguments call for variable 1, variable 2,... in iterator ( element to tuple )]

2.1 List-generated

2.1.1 Concept

[x * x for x in range (1, 11)]

Equivalent to

>>> L = []

>>> for x in range (1, 11):

... L.append (x * x)

2.1.2 Example

Please use list generation to generate list [1x2, 3x4, 5x6, 7x8, ..., 99x100]

[X*y for x, y in Zip (range (1,100,2), Range (2,100,2))]

2.2 List-generation with conditional filtering

A list-generated for loop can also be followed by an if judgment. For example:

>>> [x * x for x in range (1, 11)]

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

If we want even squares, without changing the range (), you can filter by if:

>>> [x * x for x in range (1, one) if x% 2 = = 0]

[4, 16, 36, 64, 100]

2.3 Nested List-generated

For loops can be nested, so in a list build, you can also use a multi-layer for loop to generate the list.

For the string ' ABC ' and ' 123 ', a two-layer loop can be used to generate a full array:

>>> [M + N for m in ' ABC ' for n ' 123 ']

[' A1 ', ' A2 ', ' A3 ', ' B1 ', ' B2 ', ' B3 ', ' C1 ', ' C2 ', ' C3 ']

The Loop code is translated as follows:

L = []

For M in ' ABC ':

For-N in ' 123 ':

L.append (M + N)

2.4 Formatting strings + complex list generation

2.4.1 thought

Complex, regular strings can be generated using functions

2.4.2 Example

In the resulting table, mark the score red for those who have not passed.

Hint: Red can be implemented with <TD style= "color:red" >.

D = {' Adam ': +, ' Lisa ': $, ' Bart ': 59}

# Generate Table Property string method

def generate_tr (name, score):

If score<=60:

Return ' <tr><td style= ' color:red >%s</td><td>%s</td></tr> '% (name, score)

Return ' <tr><td>%s</td><td>%s</td></tr> '% (name, score)

TDS = [Generate_tr (name,score) for name, score in D.iteritems ()]

print ' <table border= ' 1 "> '

print ' <tr><th>Name</th><th>Score</th><tr> '

print ' \ n '. Join (TDS)

print ' </table> '

Python Basics--08 Iterations & List Generation

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.