I have a list named list_1 = ["File_A","File_B","File_C","File_D"]
I want to run a loop and get four arrays as
File_A = np.array(0)
File_B = np.array(0)
File_C = np.array(0)
File_D = np.array(0)
Please reply if possible
CodePudding user response:
I strongly discouraged you to use locals()
(or globals()
or vars()
) to manipulate the variables dynamically:
list_1 = ['File_A', 'File_B', 'File_C', 'File_D']
for v in list_1:
locals()[v] = np.array(0)
Output:
>>> File_A
array(0)
>>> File_B
array(0)
>>> File_C
array(0)
>>> File_D
array(0)
Note: File_A
, File_B
, ... should be valid Python name identifiers.
CodePudding user response:
You could use dictionary objects perhaps.
list_1 = ["File_A","File_B", "File_C", "File_D"]
myFileLists = {}
for _file in list_1:
myFileLists[_file] = []
To view an element, example the list created for 'File_A':
print (myFileLists['File_A'])
CodePudding user response:
If I understand the question correctly, this seems to be an ideal case for using a dictionary. For example:
import numpy
list_1 = ["File_A", "File_B", "File_C", "File_D"]
D = {k: numpy.array(0) for k in list_1}
You can then access the numpy arrays "by name" as:
D['File_A']
...and so on