有没有办法在引用原始列表的同时将列表元素变成自变量?

Is there a way to turn list elements into independent variables while referencing the original list?

我想从一个目录中获取一种类型 (.npy) 的所有文件,并将它们转换为命名变量,这些变量使用 numpy 中的 np.load 调用 .npy 文件中的数据。

我已经使用 glob 创建了一种类型的文件列表,但是我似乎找到了继续进行的好方法。

os.chdir("/Users/Directory/")
dir_path = os.getcwd()

file_names = sorted(glob.glob('*.npy'))
file_names = file_names[:]
for f in file_names:
    print(f)
EELS 10nmIF 16nm.npy
EELS 4nmIF 16nm.npy
EELS Background.npy

我想要输出的是一组名称为的变量:

EELS 10nmIF 16nm
EELS 4nmIF 16nm
EELS Background

并且每个变量都会调用 .npy 文件中的数据,例如使用 np.load 这样基本上它看起来像这样:

EELS 10nmIF 16nm = np.load(dir_path + EELS 10nmIF 16nm.npy)
EELS 4nmIF 16nm = np.load(dir_path + EELS 4nmIF 16nm.npy)
EELS Background = np.load(dir_path + EELS Background.npy)

我不是 100% 确定,但我认为你不能在运行时用 python(或我知道的任何其他语言)分配变量名,但你可以做的是使用字典将文件名作为键,然后使用一个对象作为包含文件中数据的值

您可以使用 list comprehension 创建新的修剪文件名列表。

variables = [f[0:-4] for f in file_names]

然后你可以用这个列表的内容做任何你想做的事情,包括加载每个文件:

for v in variables:
    np.load(dir_path + v + '.npy')

或者,跳过上述步骤,直接加载所有文件:

for f in file_names:
    np.load(dir_path + f)

虽然我可能没有抓住你问题的重点,所以也许 this answer 有你需要的东西。