Python List-generated

Source: Internet
Author: User
Python List-generated

1. Generate a list

L = []for x in range (1, one):    l.append (x * x) print lprint ' \ n ' Print [x * x for x in range (1, one-by-one)]print ' \ n ' Print [x * ( x + 1) for x in range (1, 100, 2)]

2. Complex expressions

D = {' Adam ':}tds, ' Lisa ': $, ' Bart ':----= [' <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> ' print ' \ n ' d = {' Adam ': +, ' Lisa ': ', ' Bart ': }def generate_tr (name, score):    if score <:        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 b order= "1" > ' print ' <tr><th>Name</th><th>Score</th><tr> ' print ' \ n '. Join (TDS ) print ' </table> '

3. Conditional filtering

print [x * x for x in range (1, one)]print ' \ n ' Print [x * x for x in range (1, one) if x 2 = = 0]print ' \ n ' def touppers (L): 
  return [X.upper () for x in L if Isinstance (x, str)]print touppers ([' Hello ', ' World ', 101])

4. Multi-Layer expressions

print [M + N for m in ' abc ' for n ' 123 ']print ' \ n ' L = []for m in ' ABC ': for    N in ' 123 ':        l.append (m + N) Print Lp Rint ' \ n ' Print [+ * n1 + ten * n2 + n3 for N1 in range (1, ten) for N2 in range (ten) for N3 in range (ten) if N1==N3]

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.