Python Basics Getting Started list generation __python

Source: Internet
Author: User

8.1, build the list


To generate the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we can use range (1, 11):

>>> Range (1, 11)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But if you want to generate [1x1, 2x2, 3x3, ..., 10x10] how to do it. Method one is loop:

>>> L = []

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

... L.append (x * x)

...

>>> L

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

But a loop is too cumbersome, and a list-builder can use a single line of statements instead of looping to generate the list above:

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

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

This notation is a Python-specific list-builder. With a list generation, you can generate a list in very concise code.

Write list generation, the element to be generated X * x into the front, followed by the For loop, you can create a list, very useful, more than a few times, you will soon be familiar with this syntax.

Task

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

Tip:Range (1, 100, 2) can generate list [1, 3, 5, 7, 9,...], indicating: from 1 to 100, not 100, and every two to get the first value


Task code:

print [x * (x + 1) for x in range (1,100,2)]


8.2. Complex expression

(Note: This section needs to edit the code before the Sublimetext, then save as a. py file, and then the terminal starts the. py file, saves the output to an HTML file, and then opens it, and you can see the effect, and it's not clear to look at the beginning of the Python introductory article, the effect chart:




Iterations that use a for loop can iterate not only the normal list, but also the dict.

Assume the dict of the following:

D = {' Adam ': ' Lisa ': ' n ', ' Bart ': 59}

It can be turned into an HTML table by a complex list-generation:

TDS = [' <tr><td>%s</td><td>%s</td></tr> '% (name, score) for name, score in D.iteritems ()]

print ' <table> '

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

print ' \ n '. Join (TDS)

print ' </table> '

Note: The string can be formatted by%, replacing %s with the specified parameter. The join () method of a string can concatenate a list into a string.

Save the printed results as an HTML file, and you can see the effect in the browser:

<table border= "1" >

<tr><th>Name</th><th>Score</th><tr>

<tr><td>Lisa</td><td>85</td></tr>

<tr><td>Adam</td><td>95</td></tr>

<tr><td>Bart</td><td>59</td></tr>

</table>


Task

In the resulting form, for students who fail, mark the score red.

Hint: red can be <td style= "color:red" > implementation.



Task code:

D = {' Adam ': ' Lisa ': ' n ', ' Bart ': 59}

def generate_tr (name, score):

If score < 60:

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

Else

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> '


8.3. Conditional filtration


The For loop for the list generation 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 only want even squared, without changing range (), we can add if to filter:

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

[4, 16, 36, 64, 100]

With the IF condition, the current element of the loop is added to the list only if the if is judged to be True.

Task

Write a function that accepts a list and then returns all the strings in the list to uppercase and the non string elements are ignored.

Tip:

1. Isinstance (x, str) can determine whether the variable x is a string;

2. The upper () method of the string can return uppercase letters.


Task code:

def touppers (L):

return [X.upper () to X in L if Isinstance (X,STR)]


Print touppers ([' Hello ', ' World ', 101])


8.4. Multi-layer expression


A For loop can be nested, so you can also use a multi-tier for loop to generate a list in a list-generation.

For the string ' ABC ' and ' 123 ', you can use a two-tier loop to generate a full arrangement:

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

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

Translate it into looping code as follows:

L = []

For M in ' ABC ':

For n in ' 123 ':

L.append (M + N)

Task

Use the 3-tier for loop list generation to find the symmetric 3-digit number. For example, 121 is the symmetric number, because the upside from right to left is 121.


Task code:

print [1,10 x + * y + Z for x in range () for Y in range (a) for z in range (ten) if x = = Z]

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.