zoukankan      html  css  js  c++  java
  • Python 的列表生成器

    列表生成器为创建列表提供了一种简洁的方式。

    比如说,我们可以这样实现一个平方数列表

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

    或者这样迭代一个字符串来生成列表

    >>> s = 'hello world'
    >>> comp = [x for x in s if x != ' ']
    >>> print(comp)
    ['h','e','l','l','o','w','o','r','l','d']
    

    实际上,列表生成式这个概念在Python中被泛化了。不但可以生成列表,还可以生成字典 dict 和集合 set。

    >>> s = 'hello world'
    >>> comp = {x for x in s}
    >>> print(comp)
    {' ','h','d','o','l','e','w','r'}
    >>> print(type(comp))
    <class 'set'>
    

    严格来说,字典生成式是这样的语言:

    {key:value for (key,value) in iterable}
    

    而有一个 zip() 函数可以把可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

    >>> s = 'hello world'
    >>> dict_comp = {k:v for (k,v) in zip(range(11),s)}
    >>> print(dict_comp)
    {0:'h',1:'e',2:'l',3:'l',4:'o',5:' ',6:'w',7:'o',8:'r',9:'l',10:'d'}
    >>> print(type(dict_comp))
    <class 'dict'>
    

    但是,其实对于上面这个简单的例子,可以不用字典生成式,直接用 dict() 进行转换也是可以的。

    >>> s,i = 'hello world', len(s)
    >>> dict_comp = dict(zip(range(i),s))
    >>> print(dict_comp)
    {0:'h',1:'e',2:'l',3:'l',4:'o',5:' ',6:'w',7:'o',8:'r',9:'l',10:'d'}
    >>> print(type(dict_comp))
    <class 'dict'>
    
  • 相关阅读:
    javascript关于继承
    javascript组合继承
    javascript创建对象的几种模式
    Angularjs学习笔记6_table1
    Angularjs学习笔记5_form1
    Angularjs学习笔记3_datepicker
    Angularjs学习笔记2_添加删除DOM元素
    Angularjs学习笔记5_scope和$rootScope
    Angularjs学习笔记1_基本技巧
    RabbitMQ基础概念
  • 原文地址:https://www.cnblogs.com/IvyWong/p/11813717.html
Copyright © 2011-2022 走看看