简体   繁体   English

“ y中的x的x:set()”如何工作?

[英]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.

相关问题 为什么只有当我使用'x,y = y,x + y格式而不是'x = y'时,此代码才起作用? y = x + y'? - Why does this code only work when i use 'x,y = y,x + y format instead of 'x = y; y = x + y'? 使用(x == y).mean()估算精度-如何工作? - Estimating accuracy with (x == y).mean() - How does it work? 为什么 if not in(x,y) 在 python 中根本不起作用 - why does if not in(x,y) not work at all in python “any()”函数如何与“x in y for x in z”这样的迭代一起工作? - How does the "any()" function work with a iteration like "x in y for x in z"? __eq__如何对node1.x == node2.x和node 1.y == node2.y起作用? - How does __eq__ work against node1.x == node2.x and node 1.y == node2.y? 如果 y 是负数,为什么 x**y%z 不像 pow(x, y, z) 那样工作? - Why does x**y%z doesn't work like pow(x, y, z) if y is negative? Sci-Kit学习的.fit(X,y)方法是否按顺序工作,如果没有,该如何工作? - Does Sci-Kit learn's .fit(X,y) method work sequentially, if not how does it work? 在Mechanize中,如何设置ImageButton的x,y值? - In Mechanize, how to set the x,y value of ImageButton? 如何从集合中的(x,y)坐标返回x值 - How to return x value from (x,y) coordinates in a set {%url'x'y%}在Django中如何工作? - How does {% url 'x' y %} function in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM