这是我试图转换为列表理解的代码:
table = ''
for index in xrange(256):
if index in ords_to_keep:
table += chr(index)
else:
table += replace_with
有没有办法将 else 语句添加到这个理解中?
table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)
最佳答案
语法 a if b else c
是 Python 中的三元运算符,如果条件 b
为真,则计算结果为 a
- 否则,它的计算结果为 c
。它可以用在理解语句中:
>>> [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))
关于python - 是否可以在列表理解中使用 'else' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2951701/