• 列表生成式和生成器


    要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做:

    l=[x*x for x in range(1,10)]
    print (l)
    
    E:python36python3.exe E:/pj/test/test.py
    [1, 4, 9, 16, 25, 36, 49, 64, 81]
    

    列表生成式里还可以增加判断语句

    取偶数的平方

    l=[x*x for x in range(1,10) if x%2==0]
    print (l)
    
    E:python36python3.exe E:/pj/test/test.py
    [4, 16, 36, 64]

     偶数取平法,奇数不变:

    l=[x*x if x%2==0 else x for x in range(1,10)]
    print (l)
    
    E:python36python3.exe E:/pj/test/test.py
    [1, 4, 3, 16, 5, 36, 7, 64, 9]

    双层循环:

    x为1到10的偶数,y为0或者1,它们所有可能的乘积:

    l=[x*y for x in range(1,10) if x%2==0 for y in range(2)]
    print (l)
    
    E:python36python3.exe E:/pj/test/test.py
    [0, 2, 0, 4, 0, 6, 0, 8]
    

    字典通过items去遍历:

    去生成一个html表格,名字和分数,分数低于60分的标红色

    #-*-coding:utf-8-*-
    d={'李强':80,'老王':40,'小明':70}
    def get_html(td):
        print ("<table border='1'>")
        print ("<tr><th>name</th><th>score</th></tr>")
        for i in td:
            print (i)
        print ("</table>")
    l=['<tr><td>{0}</td> <td>{1}</td></tr>'.format(name,score) if score>60 
           else '<tr><td>{0}</td> <td style="color:red">{1}</td></tr>'.format(name,score) for name,score in d.items()]
    get_html(l)
    
    E:python36python3.exe E:/pj/test/test.py
    <table border='1'>
    <tr><th>name</th><th>score</th></tr>
    <tr><td>李强</td> <td>80</td></tr>
    <tr><td>老王</td> <td style="color:red">40</td></tr>
    <tr><td>小明</td> <td>70</td></tr>
    </table>
    

    生成器(Generator)

    列表生成式会受到内存限制占用很大的存储空间,这种一边循环一边计算的机制,称为生成器(Generator)。只要把列表生成式【】改成()就好了。超出迭代范围的时候就会抛出异常StopIteration。

    d={'李强':80,'老王':40,'小明':70}
    l=("{0}是{1}分".format(name,score) for name,score in d.items())
    print(next(l))
    print(next(l))
    print(next(l))
    
    E:python36python3.exe E:/pj/test/test.py
    李强是80分
    老王是40分
    小明是70分
  • 相关阅读:
    Hihocoder 1275 扫地机器人 计算几何
    CodeForces 771C Bear and Tree Jumps 树形DP
    CodeForces 778D Parquet Re-laying 构造
    CodeForces 785E Anton and Permutation 分块
    CodeForces 785D Anton and School
    CodeForces 785C Anton and Fairy Tale 二分
    Hexo Next 接入 google AdSense 广告
    如何统计 Hexo 网站的访问地区和IP
    Design and Implementation of Global Path Planning System for Unmanned Surface Vehicle among Multiple Task Points
    通过ODBC接口访问人大金仓数据库
  • 原文地址:https://www.cnblogs.com/letmeiscool/p/8508502.html
Copyright © 2020-2023  润新知