为什么你可以循环遍历for循环中的隐式元组,而不是Python中的理解? [英] Why can you loop through an implicit tuple in a for loop, but not a comprehension in Python?

查看:680
本文介绍了为什么你可以循环遍历for循环中的隐式元组,而不是Python中的理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

循环中的中的隐式元组循环是否可以,但是当你理解时,你会得到一个语法错误吗?



例如:

 我在'a',' b','c':
print(i)

'a'
'b'
'c'




$ b

但在理解中:

 > >> [i为'a','b','c'] 
文件< stdin>,第1行
[i为'a','b','c ']
$
SyntaxError:无效语法

是否有这个原因?我不确定正确的术语,所以我的搜索没有任何用处。



更新:

根据评论,这个语法 / em>对Python 2.x有效,但对Python 3.x不适用。

解决方案

这个在Python3中进行了改变,主要是为了使列表解析更加符合生成器表达式。 b

对于循环和列表推导,当使用不带圆括号的元组时,不会出现歧义,因为前者总是以冒号结尾,后者由闭括号或 for / if 关键字。

然而,发生器表达式的部分设计要求它们可以被裸函数参数:

 >>>列表(我为我在范围(3))
[0,1,2]

这会造成一些含糊不清的元组,因为任何逗号都可能引入一个新的参数:

 >>>列表(i为0,1,2)
文件stdin>,第1行
语法错误:如果没有唯一参数,生成器表达式必须加上括号

Guido van Rossum写了一篇文章,在他的Python历史博客中详细描述了这个主题的所有细节:



Is there a reason why looping through an implicit tuple in a for loop is okay, but when you do it in a comprehension you get a syntax error?

For example:

for i in 'a','b','c': 
    print(i)

'a'
'b'
'c'

But in a comprehension:

>>> [i for i in 'a','b','c']
  File "<stdin>", line 1
    [i for i in 'a','b','c']
                   ^
SyntaxError: invalid syntax

Is there a reason for this? I wasn't sure about the correct terminology, so my searches yielded nothing useful.

Update:

Per the comments, this syntax is valid for Python 2.x, but not for Python 3.x.

解决方案

This changed in Python3, mainly in order to make list comprehensions more consistent with generator expressions.

With for-loops and list comprehensions, there is no ambiguity when using a tuple with no parentheses, because the former is always terminated by a colon, and the latter by either a closing bracket or a for/if keyword.

However, part of the design of generator expressions requires that they can be used "bare" as function arguments:

>>> list(i for i in range(3))
[0, 1, 2]

which creates some ambiguity for unparenthesized tuples, because any commas may introduce a new argument:

>>> list(i for i in 0, 1, 2)
  File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument

So tuples must always be parenthesized in generator expressions, and the same restriction now also applies to list comprehensions in order to preserve consistency.

PS:

Guido van Rossum wrote a article that spells out all the details on this subject in his History of Python blog:

这篇关于为什么你可以循环遍历for循环中的隐式元组,而不是Python中的理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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