zoukankan      html  css  js  c++  java
  • Python高级特性——列表生成式(list Comprehensions)

    List Comprehensions 即列表生成式,是Python内置的强大的用来生成列表list的生成式。

    简单菜:

    >>> l = list(range(2,13))
    >>> l
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

    如果要生成[1*1,2*2,3*3,4*4,……,10*10]怎么做呢?一般的可以使用循环:

    >>> l=[]
    >>> for x in range(1,11):
    ...     l.append(x*x)
    ...
    >>> l
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    上面的例子比较简单,有时候循环太麻烦,而列表生成式则可以用一行语句替代循环实现相应的效果:

    >>> [x*x for x in range(1,11)]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    注意,使用列表生成式的时候,要把需要生成的元素x*x放在前面,后面跟上for循环。

    for循环后面还可以跟上if判断,例如,下面的例子可以生成偶数的平方:

    >>> [x*x for x in range(1,11) if x % 2==0]
    [4, 16, 36, 64, 100]

    还可以使用双循环,生成类似下面的全排列:

    >>> [m+n for m in 'abc' for n in 'xyz']
    ['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']

    类似的,我们可以实现三层、四层……循环。

    再来一个开胃菜:运用列表生成式,列出当前目录下的所有文件夹和文件,仅仅使用一行代码:

    >>> import os #导入os模块
    >>> [dir for dir in os.listdir('E:Python3.6.3')]
    ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime
    140.dll', 'workspace']

    列表生成式也可以使用两个变量来生成list:

    >>> d= {'1':'A','2':'B','3':'C'}
    >>> [k+'='+v for k,v in d.items()]
    ['1=A', '2=B', '3=C']

    练习1:把一个list中的所有字符串变成小写:

    >>> l=['I','Love','You']
    >>> [str.lower() for str in l]
    ['i', 'love', 'you']

    练习2:如果一个list中既包含字符串,又包含整数,怎么办呢?(提醒,非字符串类型的对象是没有lower()函数的,可以使用isinstance函数判断一个变量是不是指定类型):

    >>> l=['I','Love',18,'You']
    >>> [s.lower() for s in l if isinstance(s,str)]
    ['i', 'love', 'you']

    很爽!

  • 相关阅读:
    终端提示“ timed out waiting for input: auto-logout”
    shell-日志统计
    spring-file-upload-exceeds its maximum permitted size of 1048576 bytes
    全面质量管理 TQM、六西格玛、CMMI、ISO9000 关系
    GitLab: You are not allowed to force push code to a protected branch on this project.
    go 多版本管理
    glide install error
    js tab栏切换
    ES6 class命令浅识
    ES6 const命令
  • 原文地址:https://www.cnblogs.com/hiwuchong/p/8053881.html
Copyright © 2011-2022 走看看