Python complex list generative tutorial

Source: Internet
Author: User
This article mainly describes the practical use of the python list generator! Hope to help beginners! 1. Complex list-based HTML table: This article mainly describes the practical application of the python list-based syntax! Hope to help beginners!

1. Complex list-based HTML table:

Note: the string can be formatted by %, and % s can be replaced by the specified parameterization. The join () method of a string can splice a list into a string.

Mark Few scores as red:

D = {'Adam ': 95, 'Lisa': 85, 'Bart': 59}
Def generate_tr (name, score ):
If score <60
Return'% S% S'% (Name, score)
Return'% S% S'% (Name, score)
Tds = [generate_tr (name, score) for name, score in d. iteritems ()]
Print'




'Print' 'Print '\ n'. join (tds)Print'
Name Score
'

2. conditional filtering

If judgment can be added after the for loop of the list generation type:

Returns all strings in the list in uppercase. non-string elements are ignored.

Tip:

1. isintance (x, str) can be used to determine whether the variable x is a string.

2. the string upper () method 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 expressions

The for loop can be nested. Therefore, you can use a multi-layer for loop to generate a list.

For example, for strings 'ABC' and '123', you can use two-layer village replacement to generate a full arrangement.

[N + m for m in 'abc' for n in '123']

Exercise: use a three-layer nested for loop to find the symmetric 3-digit, for example, 121

Print [100 * m + 10 * n + m for m in range () for n in range ()]

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

Course recommendations:

Python online video tutorial

The above is the details of the python complex list generative tutorial. For more information, see other related articles in the first PHP community!

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.