是否有可能在python列表理解中使用“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) 
	
 语法a if b else c是Python中的三元运算符,如果条件b为真,则计算结果为c – 否则计算结果为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)) 
 如果你想要一个else你不想过滤列表理解,你希望它遍历每个值。  true-value if cond else false-value作为语句, true-value if cond else false-value可以使用true-value if cond else false-value ,并从结尾删除filter: 
 table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15)) 
 要在Python编程中使用列表推导中的else ,可以尝试下面的代码片段。 这将解决你的问题,这个片段是在python 2.7和python 3.5上testing的。 
 obj = ["Even" if i%2==0 else "Odd" for i in range(10)] 
另外,我认为列表理解是最有效的方法吗?
也许。 列表理解不是固有的计算效率。 它仍然在线性运行。
从我个人的经验来看:通过用上面的for-loop / list-appendingtypes结构replace列表parsing(特别是嵌套的),大大减less了处理大数据集的时间。 在这个应用程序中,我怀疑你会注意到一个区别。
很好的答案,但只是想提一个“通过”关键字在列表理解(如上面提到的例子)中的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上testing和testing的。 错误如下:
 newlist2 = [x if x > 30 else pass for x in list1 ] SyntaxError: invalid syntax 
所以,尽量避免在列表parsing中使用pass-es