将字典的键值对分配用作 for 循环中的迭代器 [英] Using key value pair assignments for a dictionary as an iterator in a for loop

查看:22
本文介绍了将字典的键值对分配用作 for 循环中的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 Python 中遇到了这个很酷的 hack.

这个:

d = {}对于 i, d[i] 在 enumerate('abc'):经过


<预><代码>>>>d{0:'a',1:'b',2:'c'}>>>

这将键值对分配给迭代器中的空字典.

我想知道 Cython 后端如何解析它,我的期望是它正在通过解包赋值进行解析.但是很高兴知道它的实际 Cython 实现,以及是否建议这样做?

我知道我可以简单地做:

d = {}对于 i, v in enumerate('abc'):d[i] = v

但是上面很酷的 hack 可以用更短的代码来做到这一点,但我不确定这在 Python 中是否被认为是好的做法.

我从没见过有人用过这个...

解决方案

您不必阅读 CPython 代码,因为该行为已在 Python 文档中定义.

如果您阅读了 for 声明的文档for 语句中的目标列表使用标准赋值规则:

<块引用>

使用标准将每个项目依次分配给目标列表赋值规则(参见赋值语句)

如果您阅读了赋值语句的规则,您可以看到分配的目标列表中的每一项都是按从左到右的顺序分配的:

<块引用>

赋值语句计算表达式列表(记住这可以是单个表达式或逗号分隔的列表,后者产生一个元组)并将单个结果对象分配给每个目标列表,从左到右.

因此,在 for 循环的第一次迭代中,生成了元组 0, 'a':

for i, d[i] in enumerate('abc')

执行与以下等效的赋值语句:

i, d[i] = 0, 'a'

首先将 0 分配给 i 因为它在左边,然后将 'a' 分配给 d[i],计算结果为 d[0],有效地使 d[0] = 'a'.

其余的迭代也是如此.

I just recently came across this cool hack in Python.

This:

d = {}
for i, d[i] in enumerate('abc'):
    pass


>>> d
{0: 'a', 1: 'b', 2: 'c'}
>>> 

This assigns key value pairs to a empty dictionary from the iterator.

I would like to know how Cython backend parses this, my expectation is that it's being parsed with unpacking assignment. But it would be nice to know the actual Cython implementation of this, and also if doing this is recommended or not?

I know I just can simply do:

d = {}
for i, v in enumerate('abc'):
    d[i] = v

But the cool hack above can do this with shorter code, but I am not sure if it is considered good practice in Python.

I never seen anybody use this...

解决方案

You don't have to read CPython code since the behavior is defined in the Python documentation already.

If you read the documentation of the for statement, the target list in a for statement uses rules of a standard assignment:

Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements)

And if you read the rules for assignment statements, you can see that each item in the target list of an assignment is assigned to in a left-to-right order:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

So in the first iteration of your for loop, where a tuple 0, 'a' is generated:

for i, d[i] in enumerate('abc')

An assignment statement equivalent to the following is executed:

i, d[i] = 0, 'a'

which assigns 0 to i first since it's on the left, and then 'a' to d[i], which evaluates to d[0], effectively making d[0] = 'a'.

The same goes for the rest of the iterations.

这篇关于将字典的键值对分配用作 for 循环中的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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