Python Complex list Generation tutorial

Source: Internet
Author: User
This article mainly explains the actual application of the Python list generation formula! Hope to be helpful to beginners!

1. Complex list-generated HTML table:

Note: The string can be formatted in% with the specified parameterization instead of%s. The join () method of a string can be used to stitch a list into a string.

Mark not a few scores as red:

D = {' Adam ': +, ' Lisa ': $, ' Bart ': 59}
def generate_tr (name, score):
If score < 60
Return ' <tr><td>%s</td><td style= ' color:red >%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> '

2. Conditional filtering

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

Returns all strings in the list as uppercase, and non-string elements are ignored

Tips:

1, isintance (X,STR) can determine whether the variable x is a string

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

def touppers (L):
return [X.upper () for x in L if Isinstance (X,STR)]

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

3. Multi-layer expression

For loops can be nested, so the list can be generated using a multi-layer for loop

such as: For the string ' ABC ' and ' 123 ', you can use the two-storey village exchange, generate the full array

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

Exercise: Use a three-layer nested for loop to find the symmetric 3-digit number such as 121

Print [100*m+10*n+m for M in range (1,10) for n in range (0,10)]

L=[]
For x in range (1,10):
For Y in range (10):
For z in range (1,10):
If X==z:
L.append (100*x+10*y+z)
Print L

Recommended courses:

Python online video tutorial

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.