下面是我试图转换为列表理解的代码:
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))
语法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))
很棒的答案,但只是想提到一个gotcha,“pass”关键字将无法在列表的if/else部分理解(如上面提到的例子中所示)。
#works
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else x**2 for x in list1 ]
print(newlist2, type(newlist2))
#but this WONT work
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else pass for x in list1 ]
print(newlist2, type(newlist2))
这已经在python 3.4上进行了尝试和测试。
错误如下:
newlist2 = [x if x > 30 else pass for x in list1 ]
SyntaxError: invalid syntax
因此,尽量避免在列表推导式中传递