[英]How can I import variables from a .py file into a list, so that I can use the random module on that list?
I have a python file which includes around 60 lines of variables which are file imports (for pygame).我有一个 python 文件,其中包括大约 60 行文件导入变量(用于 pygame)。 This is the
imports.py
file, it contains only variables, nothing else.这是
imports.py
文件,它只包含变量,没有其他内容。 How can I import these into a list in my main.py
?如何将这些导入到我的
main.py
列表中?
imports.py进口.py
import pygame
pygame.init()
one_surf = pygame.image.load("*")
two_surf = pygame.image.load("*")
three_surf = pygame.image.load("*")
four_surf = pygame.image.load("*")
five_surf = pygame.image.load("*")
.
.
.
Perhaps slightly rearrange your code like this:也许像这样稍微重新排列您的代码:
imports.py
import pygame
pygame.init()
surf = [
pygame.image.load("*"),
pygame.image.load("*"),
pygame.image.load("*"),
pygame.image.load("*"),
pygame.image.load("*"),
... ]
something_else.py
from imports import surf
then you can access what was prevously called three_surf
with surf[2]
然后您可以使用
surf[2]
访问以前称为three_surf
的内容
Using a dictionary would provide the same functionality as putting variables into a list because you can refer to each image based on a name/value.使用字典将提供与将变量放入列表相同的功能,因为您可以根据名称/值引用每个图像。
import pygame
pygame.init()
surf = {
'one_surf': pygame.image.load("*"),
'two_surf': pygame.image.load("*"),
'three_surf': pygame.image.load("*"),
'four_surf': pygame.image.load("*"),
'five_surf': pygame.image.load("*")
}
Storing the information in a dictionary means that you can reference each image based on a key: surf['one_surf']
holds the same value as the previous one_surf
variable.将信息存储在字典中意味着您可以基于键引用每个图像:
surf['one_surf']
保存与前一个one_surf
变量相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.