zoukankan      html  css  js  c++  java
  • 列表生成式和生成器

    要生成[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分
  • 相关阅读:
    OC之runtime面试题(一)
    OC之runtime的(isKindOfClass和isMemberOfClass)
    OC之runtime(super)
    OC中的__block修饰符
    iOS录音及播放
    webpack5升级过程遇到的一些坑?
    (转)iOS工具--CocoaPods 安装使用总结
    iOS学习--NSObject详解
    iOS学习--通过ipa包如何获取图片资源
    ‘A downloaded software component is corrupted and will not be used. ‘ while publish an iOS app to apple store via Xcode
  • 原文地址:https://www.cnblogs.com/letmeiscool/p/8508502.html
Copyright © 2011-2022 走看看