且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在列表理解中使用"else"?

更新时间:2023-11-29 08:12:46

语法a if b else c是Python中的三元运算符,如果条件b为true,则结果为a-否则,其结果为.可用于理解语句:

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

以您的示例为例,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))