是否可以在列表理解中使用"else"? [英] Is it possible to use 'else' in a list comprehension?

查看:65
本文介绍了是否可以在列表理解中使用"else"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我试图转变为列表理解的代码:

Here is the code I was trying to turn into a list comprehension:

table = ''
for index in xrange(256):
    if index in ords_to_keep:
        table += chr(index)
    else:
        table += replace_with

是否可以将else语句添加到此理解中?

Is there a way to add the else statement to this comprehension?

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

推荐答案

语法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))

这篇关于是否可以在列表理解中使用"else"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆