[英]how does “x:set() for x in y” work?
I was looking at a python code which implemented topological sort and found the following code 我正在查看一个实现拓扑排序的python代码,发现以下代码
data.update({item:set() for item in extra_items_in_deps})
I know what data.update
does but am not sure how this: 我知道
data.update
做什么,但是不确定如何:
item:set() for item in extra_items_in_deps
works. 作品。
This is a dictionary comprehension. 这是字典的理解。 It has the following syntax:
它具有以下语法:
{ k: v for item in sequence }
This will create a dictionary entry for every item
in sequence
with the key k
and the value v
. 这将为每个
item
按键k
和值v
sequence
创建字典条目。
For example, the following will create a dictionary with the keys from the sequence (1, 2, 3)
, and the squared number as the value: 例如,下面的代码将创建一个字典,该字典使用序列
(1, 2, 3)
的键并将平方数作为值:
>>> { x: x**2 for x in (1, 2, 3) }
{1: 1, 2: 4, 3: 9}
In your case, you have the following dictionary comprehension: 对于您而言,您具有以下字典理解:
{ item: set() for item in extra_items_in_deps }
This will create a dictionary with the keys from extra_items_in_deps
and create a new set for each key. 这将使用
extra_items_in_deps
的键创建一个字典,并为每个键创建一个新集合 。 So assuming extra_items_in_deps = [1, 2, 3]
, it's equivalent to this dictionary: 因此,假设
extra_items_in_deps = [1, 2, 3]
,则等效于此字典:
{ 1: set(), 2: set(), 3: set() }
This dictionary is then passed to data.update()
which updates the dictionary data
with the key-value pairs from the passed dictionary. 然后将此字典传递给
data.update()
,该文件使用传递的字典中的键值对更新字典data
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.