Comprensión de dictados anidados de Python con conjuntos

¿Alguien puede explicar cómo hacer comprensiones de dictados anidados?

>> 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

Me hubiera gustado:

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

Solo le pregunté a un Pregunta anterior 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?

preguntado el 09 de enero de 11 a las 11:01

1 Respuestas

Just reverse the order of the two loops:

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

Respondido el 09 de enero de 11 a las 14:01

This works. However I read in the manual ( that "Special care has to be taken for the nested list comprehension: To avoid apprehension when nesting list comprehensions, read from right to left." Why doesn't this apply? - atp

@Jasie Because what we are doing here is not nested list comprehension. Nested list comprehension is like [ [i*j for j in range(3)] for i in range(3)]. The tool we use here is not list comprehension at all, it is a generator expression. - satoru

From PEP 202 (, according to the BDFL: The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops. The point isn't which type of expression we are using, it is the nested-for-loop syntax of the list comprehension. - Katriel

I see, thanks for the explanation + link, @Satoru.Logic & @katriealex. - atp

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.