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']

    很爽!

  • 相关阅读:
    【妖精眼镜】
    神兽保佑-代码无BUG
    Eclipse常用快捷键 及 不格式化注释
    Android dialog 全屏
    eclipse 改变颜色,背景
    GOOGLE和百度的长域名
    Android在ArrayAdapter<>里如何得到List<>的Items
    Android 仿微信朋友圈发动态功能(相册图片多选)
    Android 让GridView的高度为Wrap_content根据内容自适应高度
    C++中函数的返回值
  • 原文地址:https://www.cnblogs.com/hiwuchong/p/8053881.html
Copyright © 2011-2022 走看看