Frage

I would like to make a list comprehension with multiple for. To make it more difficult, I have dependencies between the two levels. The higher, app.containers is a list of containers, and it contains some contents, also iterable.

This dictionary, at the end, should contain some pointers to the whole application contents, accessible by its name, prefixed with the one of its containers.

prefixed_names = {".".join(container.name, content.name): content
                  for content in container.contents
                  for container in app.containers}

Python throws a NameError, arguying that container is not defined.

War es hilfreich?

Lösung

A list comprehension is a convenient way of writing nested for loops. The first for expression is the outmost for so you need to swap the order in which you have written your for expressions. As an example:

>>> [ a+b for a in 'san' for b in '123' ]
['s1', 's2', 's3', 'a1', 'a2', 'a3', 'n1', 'n2', 'n3']

>>> for a in 'san':
...     for b in '123':
...             print a+b,
...
s1 s2 s3 a1 a2 a3 n1 n2 n3

Andere Tipps

In the expresstion

... for content in container.contents for container in app ....

you have an internal variable container which will replace the external variable container. See if

... for content in container.contents for c in app ....

helps. Here, even I cant figure out which container you want to refer to in the join statement.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top