• [翻译]Python List Comprehensions: Explained Visually || Python列表解析式


    原文1地址: http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

    原文2地址: http://blog.teamtreehouse.com/python-single-line-loops

    前言

    进一步学习Python之后,发现了Python有别于C++的一些语法,其中比较有代表性的就是在写FOR LOOP的时候,Python的一些很简洁但是不太容易理解的表达.这种表达式叫做列表解析式(List Comprehensions).

    上面的原文很详细的介绍了这个语法,我截取其中最常用的一种用法翻译并且也是记录一下.

    原文1段落翻译

    每一个列表解析式(List Comprehensions)都能写成一个FOR循环,但是并不是每一个FOR循环都能写成列表解析式(List Comprehensions).

    那么什么时候使用列表解析式(List Comprehensions)呢?就得靠一直的练习,练习多了,就能判断出哪些问题可以用列表解析式(List Comprehensions)解决.

    如果你的FOR循环能写成下面这个样子,那么就能该写为列表解析式(List Comprehensions).

    new_things = []
    for ITEM in old_things:
        if condition_based_on(ITEM):
            new_things.append("something with " + ITEM)

    改写为列表解析式(List Comprehensions)如下

    new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]

    原文2段落翻译

     列表解析式(List Comprehensions)是什么

    列表解析式(List Comprehensions)是一个通过FOR循环自己生成的一个LIST,这是Python的一个特色,格式是这样的

    [thing for thing in list_of_things]
  • 相关阅读:
    scheduletask任务调度(2间隔时间)
    scheduletask任务调度
    初始webservice
    ssh整合
    aop
    自定义框架(MyMvc)
    数据校验
    原生态ajax
    struts2国际化
    文件下载
  • 原文地址:https://www.cnblogs.com/wtang/p/7985433.html
Copyright © 2020-2023  润新知