是否可以在列表理解中使用“ else”?[重复]

发布于 2021-01-29 14:58:04

这个问题已经在这里有了答案

如果/否则列表理解
(11个答案)

去年关闭。

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

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)
关注者
0
被浏览
76
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    语法a if b else c是Python中的三元运算符,a其条件b为true;否则为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))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看