开发者

Python for x in list basic question

I am trying to create a function which will load a whole lot of images and map them to appropriate names in PyGame. I'm not all that great with python and this really has me stuck. My current code is this:

tile1 = pygame.image.load("/one.bmp")
tile2 = pygame.image.load("/two.bmp")
tile3 = pygame.image.load("/three.bmp")

and it keeps going on for about 20 til开发者_开发问答es. The thing is I just found out that I need a lot more and was wondering how I could do this using a for x in y loop. My basic idea was:

tile = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [1,2,3]
for tile in tile:
    tilelist[x] = pygame.image.load(tile)

or something like that but I'm not quite there. I was also wondering if it could be done using dictionaries.

Any help would be appreciated, thanks :)


List comprehensions to the rescue.

tiles = ['/one.bmp', '/two.bmp', '/three.bmp']
tilelist = [pygame.img.load(tile) for tile in tiles]

As @isakkarlsson commented,

...or easier(?) tilelist = map(pygame.img.load, tiles)


To load the data

tile = ['/one.bmp', '/two.bmp', '/three.bmp']
imageMap = {}
for t in tile:
    imageMap[t] = pygame.img.load(t)

Then you have all the data in a dictionary and can loop through the file names using imageMap.keys() or the index directly into the dictionary to get a particular image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜