美文网首页
Python list 生成式(推导式list comprehe

Python list 生成式(推导式list comprehe

作者: dawsongzhao | 来源:发表于2017-12-02 16:51 被阅读443次

    在list生成式中嵌套if else

    如果按中文习惯写嵌套列表生成式可能写出如下的错误语法

    >>> [x for x in range(1, 10) if x % 2 else x * 100]
      File "<stdin>", line 1
        [x for x in range(1, 10) if x % 2 else x * 100]
                                             ^
    SyntaxError: invalid syntax
    

    Python的语法是按英文阅读方式设计的,因此,正常的方式应该是

    >>> [ x if x%2 else x*100 for x in range(1, 10) ]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]
    

    或者用更简洁的形式[false,true][condition] is the syntax

    >>> [[x*100,x][x %2] for x in range(1,10)]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]
    

    更多阅读

    通过示例学习Python列表推导
    if/else in Python's list comprehension?
    python one-line list comprehension: if-else variants
    if else in a list comprehension [duplicate]

    相关文章

      网友评论

          本文标题:Python list 生成式(推导式list comprehe

          本文链接:https://www.haomeiwen.com/subject/phwnbxtx.html