zoukankan      html  css  js  c++  java
  • 零基础学python-19.12 总结列表解析与字典解析

    这一章节我们来总结一下列表解析与字典解析的语法。

    1.列表解析

    (1){1,2,3}等同于set([1,2,3])

    >>> aList={1,2,3}
    >>> bList=set((1,2,3))
    >>> aList is bList
    False
    >>> aList==bList
    True
    >>> 


    (2)列表解析就是使用set函数强迫生成器表达式生产所有值

    >>> aList={x for x in range(5)}
    >>> aList
    {0, 1, 2, 3, 4}
    >>> g=(x for x in range(5))
    >>> g
    <generator object <genexpr> at 0x01E692D8>
    >>> set(x for x in range(5))
    {0, 1, 2, 3, 4}


    (3)在列表解析过程中,可以使用任意函数对相应的对象进行运算

    >>> aList={x*x for x in range(5)}
    >>> aList
    {0, 1, 9, 16, 4}
    >>> aList={x**3 for x in range(5)}
    >>> aList
    {0, 1, 8, 27, 64}
    >>> def test(x):
    	return x+1
    
    >>> aList={test(x) for x in range(5)}
    >>> aList
    {1, 2, 3, 4, 5}
    >>> 


    2.字典解析

    (1)使用for

    >>> aList={'a','b','c','d'}
    >>> bList={1,2,3,4}
    >>> aDict={x:y for (x,y) in zip(aList,bList)}
    >>> aDict
    {'a': 1, 'd': 2, 'c': 3, 'b': 4}
    >>> 


    (2)使用dict函数

    >>> aList={'a','b','c','d'}
    >>> bList={1,2,3,4}
    >>> aDict=dict(zip(aList,bList))
    >>> aDict
    {'a': 1, 'd': 2, 'c': 3, 'b': 4}
    >>> 


    (3)在生成的过程中可以使用函数进行运算

    >>> aList={'a','b','c','d'}
    >>> bList={1,2,3,4}
    >>> aDict={x:y**2 for (x,y) in zip(aList,bList)}
    >>> aDict
    {'a': 1, 'd': 4, 'c': 9, 'b': 16}
    >>> 


    上面的所有解析都是一次性构建所有的结果,如果需要根据需求生产结果,那么上面的代码换成生成器表达式会更加的合适。

    列表解析:

    >>> g=(x for x in range(5))
    >>> next(g)
    0
    >>> next(g)
    1


    字典解析:

    >>> g=((x,x*x) for x in range(10))
    >>> next(g)
    (0, 0)
    >>> next(g)
    (1, 1)
    >>> 


    对于字典解析,笔者暂时对于其他的构建不熟悉,暂时只是找到这种特殊的解析方式。

    3.扩展

    我们在原来的基础上扩展if的使用

    >>> aList={x*x for x in range(5) if x%2==0}
    >>> aList
    {0, 16, 4}
    >>> 


    总结,这一章节我们简单总结了列表解析与字典解析。

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    python学习-类属性和实例属性
    python学习-名字管理
    phalcon安装-遇坑php-config is not installed 解决方法
    利用scp 远程上传下载文件/文件夹
    linux tar打包
    ELK logstash 启动慢的解决方法
    shell脚本学习
    ELK日志系统:Filebeat使用及Kibana如何设置登录认证(转)
    elastic5.4安装错误解决
    CentOS 6、7 安装 Golang
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896700.html
Copyright © 2011-2022 走看看