Creating a single list with multiple instances of objects from a second list in Python

I am trying to create a list of tiles for a board game from an xml file that contains a description of the fragments. The xml file describes each type of tile and the number of tiles of this type.

So far, I have the following code that creates a list with exactly one of each tile type:

    [Tile(el.id) for el in <tile descriptions>]

I would like to create a list with the appropriate amount of each fragment, for example. something like that:

    [Tile(el.id) * <el.n_tiles> for el in <tile descriptions>]

Is there an elegant one-liner to do this, or do I need to do this for a long time, creating a list for each type of tile and then concatenating?

+5
source share
2 answers

What about:

[Tile(el.id) for el in <tile descriptions> for _ in range(el.n_tiles)]
+3
source

, , :

[Tile(el.id) * <el.n_tiles> for el in <tile descriptions>]

:

[[Tile(el.id) for i in range(<el.n_tiles>)] for el in <tile descriptions>]

, :

[Tile(el.id) for el in <tile descriptions> for i in range(<el.n_tiles>)]

, ( ) itertools.chain.from_iterable.

, . : -)

+3

All Articles