在列表推导式中可以使用'else'吗?
这是我想要转换成列表推导式的代码:
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)
6 个回答
18
如果你想要一个 else
,那么你就不想在列表推导式中过滤掉任何值,而是希望它能遍历每一个值。你可以用 true-value if cond else false-value
这样的写法来替代原来的语句,并且把最后的过滤条件去掉:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
24
在Python编程中,如果你想在列表推导式中使用else
,可以试试下面的代码片段。这段代码可以解决你的问题,已经在Python 2.7和Python 3.5上测试过了。
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
449
在Python中,语法 a if b else c
是一个三元运算符。它的意思是:如果条件 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))