zoukankan      html  css  js  c++  java
  • 列表推导式

    Date: 2019-05-28

    Author: Sun

    什么是列表推导式?

    ​ 列表推导能非常简洁的构造一个新列表:只用一条简洁的表达式即可对得到的元素进行转换变形。

    格式

    [表达式 for 变量 in 列表] 或者 [表达式 for 变量 in 列表 if 条件]

    result = []
    for value in collection:
        if condition:
            result.append(expression)  
    

    案例分析

    例子1:

    mlist  = []
    for x in range(1,5):
        if x > 2:
            for y in range(1,4):
                if y < 3:
                    mlist.append(x*y)
    

    修改为列表推导式,如下:

    [x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]
    

    例子2:

    循环获取1~10之间的每个元素的平方列表

    #for循环
    list = []
    for x in range(10):
        list.append(x**2)
    

    修改为列表推导式如下:

    [x**2 for x in range(10)]
    

    例子3:

    偶数的平方列表

    list1=[]
    for x in range(10):
        if x%2 == 0:
            list1.append(x**2)
    

    修改为列表推导式

    [x**2 for x in range(10) if x%2 == 0]
    

    例子4:

    求出30以内所有的能被3整除的数的平方列表

    def squared(x):
        return x * x
    
    multiples = [squared(i) for i in range(30) if i % 3 is 0]
    print(multiples)    
    
    

    列表推导式改造成生成器

    使用()生成generator

    将推导式的[]改成()即可得到生成器。

    将上述列表推导式的 [] 改成 () 就成了生成器

    multiples = (i for i in range(30) if i % 3 is 0)
    print(type(multiples))   
    #  Output: <type 'generator'>
    
    

    关于生成器见 下一节 《2_迭代器,生成器》

    字典推导式

    字典推导和列表推导的使用方法是类似的,只不过将中括号该改成大括号。

    案例1:

    快速更换key和value

    mcase = {'a': 20, 'b': 54}
    mcase_frequency = {v: k for k, v in mcase.items()}
    print mcase_frequency
    #  Output: {20: 'a', 54: 'b'}
    
    

    案例2:(此例子在面试过程中笔试命中率达到70%)

    通过zip对象+两个字符型列表组成字典

    x = ['A', 'B', 'C', 'D']
    y = ['a', 'b', 'b', 'd']
    mdict = {i: j for i, j in zip(x, y)}
    print(mdict)
    
    

    案例3:

    将如下二维列表 [(‘name’,’tongpan’),(‘age’,28),(‘height’, 178)] 转换成字典

    myinfo = [('name', 'tongpan'), ('age', 28), ('height', 178)]
    dic_myinfo = {key: value for (key, value) in myinfo}
    print(dic_myinfo)
    
    

    集合推导式

    它们跟列表推导式也是类似的。 唯一的区别在于它使用大括号{}

    { expr for value in collection if condition }

    squared = {x ** 2 for x in [1, 1, 2]}
    print(squared)
    # Output: set([1, 4])
    
    

    用集合推导建字符串长度的集合

    strings = ['a','is','with','if','file','exception']
    res = {len(s) for s in strings}
    print(res)
    
    
  • 相关阅读:
    Android CTS 测试
    Cygwin 不兼容Win7 64
    真滴有太多不懂的的东西,有点扛不住了。
    ffmpeg yasm not found, use disableyasm for a crippled build
    手机搜索不到 Connectify
    Android ICS 横竖屏切换时不销毁Activity
    MinGw\bin\ar.exe: libavcodec/: Permission denied
    Cannot complete the install because one or more required items could not be found.
    Eclipse 启动时报错 JVM terminated. Exit code=1
    【Java 从入坑到放弃】No 5. 控制流程
  • 原文地址:https://www.cnblogs.com/sunBinary/p/10940965.html
Copyright © 2011-2022 走看看