简体   繁体   English

Python嵌套字典理解集

[英]Python nested dict comprehension with sets

Can someone explain how to do nested dict comprehensions? 有人可以解释如何做嵌套dict理解吗?

>> l = [set([1, 2, 3]), set([4, 5, 6])]
>> j = dict((a, i) for a in s for i, s in enumerate(l))
>> NameError: name 's' is not defined

I would have liked: 我本来希望:

>> j
>> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1}

I just asked a previous question about a simpler dict comprehension where the parentheses in the generator function were reduced. 我只是问了一个关于更简单的字典理解的问题,在该问题中生成器函数的括号被减少了。 How come the s in the leftmost comprehension is not recognized? 为什么最左边的理解中的s不被识别?

只需颠倒两个循环的顺序即可:

j = dict((a, i) for i, s in enumerate(l) for a in s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM