理解语法不一致? [英] Inconsistent comprehension syntax?

查看:107
本文介绍了理解语法不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是偶然发现了python语法中的一个缺陷 - 或者我错过了什么。

I just stumbled over what seems to be a flaw in the python syntax-- or else I'm missing something.

看到这个:

[x for x in range(30) if x % 2 == 0]

但这是语法错误:

[x for x in range(30) if x % 2 == 0 else 5]

如果您有 else 子句,你必须写:

If you have an else clause, you have to write:

[x if x % 2 == 0 else 5 for x in range (30)]

但这是语法错误:

[x if x %2 == 0 for x in range(30)]

我缺少什么?为什么这么不一致?

What am I missing? Why is this so inconsistent?

推荐答案

你在这里混合语法。这里有两个不同的概念:

You are mixing syntax here. There are two different concepts at play here:


  • 列表理解语法。这里如果充当过滤器;是否包含迭代中的值。没有 else ,因为那是不包括的情况。

  • List comprehension syntax. Here if acts as a filter; include a value in the iteration or not. There is no else, as that is the 'don't include' case already.

A 条件表达式。这必须始终返回一个值,即'true'或'false'表达式的结果。

A conditional expression. This must always return a value, either the outcome of the 'true' or the 'false' expression.

这篇关于理解语法不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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