Python嵌套字典理解与集合 [英] Python nested dict comprehension with sets
本文介绍了Python嵌套字典理解与集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释嵌套字典的理解方式吗?
Can someone explain how to do nested dict comprehensions?
>> 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
我会喜欢:
>> 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
只是逆转两个循环的顺序:
Just reverse the order of the two loops:
j = dict((a, i) for i, s in enumerate(l) for a in s)
这篇关于Python嵌套字典理解与集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文