简体   繁体   中英

How do I find a preexisting variable with a list of strings in Python?

How do I find a preexisting variable with a list of strings in Python?

I have a list of strings, such as:

letters = ["C", "A", "M", "P"]

and a set of preexisting variables, such as:

C = pygame.image.load("resources/menu icons/imgC.png")
A = pygame.image.load("resources/menu icons/imgA.png")
M = pygame.image.load("resources/menu icons/imgM.png")
P = pygame.image.load("resources/menu icons/imgP.png")

I am looking for a command such as:

surface.blit(letters[0])

to display the image on the screen. Can anyone help?

I'd probably go for a dictionary.

d = {
    'C': pygame.image.load("resources/menu icons/imgC.png"),
    'A': pygame.image.load("resources/menu icons/imgA.png"),
    'M': pygame.image.load("resources/menu icons/imgM.png"),
    'P': pygame.image.load("resources/menu icons/imgP.png")
    }

Then you can look stuff up that way

d['A']

Or

d[letters[1]]

Cyber's method has the advantage of keeping your namespace more organized, but it's also nice to know about globals , with which you can do this:

surface.blit(globals()[letters[0]])

(assuming C , A , M , P are defined in the global namespace. If they are local variables, you could use vars() instead of globals() .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM