[英]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? 如何在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: Cyber的方法具有保持命名空间更有条理的优点,但了解全局变量也很好,您可以使用它来执行此操作:
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()
.) (假设
C
, A
, M
, P
在全局命名空间中定义。如果它们是局部变量,则可以使用vars()而不是globals()
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.