为什么这个列表理解会给我一个语法错误? [英] Why is this list comprehension giving me a syntax error?

查看:114
本文介绍了为什么这个列表理解会给我一个语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表理解。

return [tower for tower in state if tower != space else []]

但是当我运行它时,python吐出这个错误:

But when I run it, python spits back this error:

return [tower for tower in state if tower != space else []]  
                                                      ^
    SyntaxError: invalid syntax

如果我删除else语句,它运行正常。我是否以某种方式将else语句写错了?

If I remove the else statement, it runs fine. Am I writing the else statement wrong somehow?

推荐答案

列表推导支持如果但不是 else 因为 if 部分过滤元素,你要么包含一个元素,要么你没有包含它,一个布尔选择。

List comprehensions support if but not else because the if section filters elements, you either include an element or you don't include it, a boolean choice.

如果您想使用条件表达式为的可迭代部分>循环,使用括号:

If you wanted to use a conditional expression to build the iterable part of the for loop, use parentheses:

return [tower for tower in (state if tower != space else [])]  

但我怀疑你想改变元素表达式中表达式的值相反;这不是过滤,你只是为某些项目产生不同的值。使用条件表达式来生成您的值:

but I suspect that you wanted to alter the value of the expression in the element expression instead; that's not filtering, you are simply producing a different value for certain items. Use a conditional expression to produce your values:

return [tower if tower != space else [] for tower in state]  

或者如果你真的想要过滤,只需省略 else

or if you really wanted to filter, simply omit the else:

return [tower for tower in state if tower != space]  

在构建列表推导时,请记住您需要从左到右读取表达式为嵌套,最后的表达式在左侧生成结果:

When constructing a list comprehension, remember that you need to read the expression as nested from left to right, with the final expression producing the result out on the left:

[element_producing_expression for name in iterable if filter_expression]

道德等价于:

for name in iterable:
    if filter_expression:
        element_producing_expression

你可以在哪里se尽可能多的嵌套循环和 if 过滤器,如你的用例所需。

where you can use as many nested loops and if filters as your use case requires.

我上面描述的三个选项是相同如下:

The three options I described above are then the same as:

# conditional expression producing the iterable
for tower in (state if tower != space else []):
    tower 

# conditional expression in the element expression
for tower in state:
    tower if tower != space else [] 

# filtering expression with no else
for tower in state:
    if tower != space:
        tower

这篇关于为什么这个列表理解会给我一个语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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