Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create single list with multiple instances of objects from second list in Python

I'm trying to build a list of tiles for a board game from an xml file which contains a description of the tiles. The xml file describes each tile type, and the number of tiles of that type.

So far, I've got the following code which creates a list with exactly one of each tile type:

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

I'd like to create a list with the appropriate number of each tile, e.g. something like this:

    [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 it long-hand by creating a list for each tile type and then concatenating?

like image 996
Stefan Avatar asked Apr 01 '13 16:04

Stefan


1 Answers

How about:

[Tile(el.id) for el in <tile descriptions> for _ in range(el.n_tiles)]
like image 75
NPE Avatar answered Sep 28 '22 05:09

NPE