python - 这个 Python 语句是什么意思?

标签 python

我正在写一个解析器,在调试它的过程中,我发现显然,这是合法的 Python:

for []    in [[]]: print 0

这也是(!):

for [][:] in [[]]: print 0

我不怪解析器弄糊涂了......在弄清楚如何解释它时遇到了麻烦!

这句话到底是什么意思?

最佳答案

在执行方面:没有。

for 循环本身在一个空列表上循环,因此不会发生迭代。

这是一件好事,因为 for [] 意味着:将循环中的每个条目分配给 0 个变量。后半部分可能是你不解的地方。

该声明是合法的,因为 target token token_list允许您将序列中的值分配给同样大的变量名称序列;我们称这个元组拆包。下面是目标列表比较有用的例子,在赋值和删除中:

(a, b, c) = range(3)
del a, b, c

您可以在 for 循环中执行相同的操作:

nested = [[1,2,3], [4,5,6]]
for a, b, c in nested:
    print nested

target_list 标记可以同时使用元组和列表,这也是合法的:

[a, b] = (1, 2)

但是,在 Python 中,列表可以为空。因此,以下是合法的,但不合理:

[] = []

最后,也是这样:

nested_empty = [[], [], []]
for [] in nested_empty:
    pass

目标列表更有趣:

[][:] = [1, 2, 3]

现在左边在赋值中使用了一个切片。来自文档:

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.

所以这里我们不再使用元组拆包;相反,我们用右侧列表替换了左侧列表的一部分。但是因为在我们的示例中,左侧列表是匿名列表文字,因此生成的更改列表再次丢失。

但是因为这样的赋值在 for 循环中也是合法的,所以下面是合法的语法,尽管相当荒谬:

for [][:] in [range(i) for i in range(10)]: print 0

关于python - 这个 Python 语句是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659781/

相关文章:

python - PEP-492 中的协同程序会绕过 Python 3.5 中的 GIL 吗?

python - 使用 Cloudant-Python 库通过 API key 进行连接

python - 将过滤后的列表传递给django中的模板后再次获取所有对象

python - Python变量行中的for循环问题未定义

python - 解析并获取日志文件中两个时间对象之间的值

python - 使用 pyevolve 恢复优化

python - 将列表中的值附加到字典中

python - 如何使Open CV在已部署的Web应用程序上工作

python - Python 中的装饰器函数

python 日历小部件 - 返回用户选择的日期