简体   繁体   中英

Python nested dict comprehension with sets

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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