0

I need to create several NumPy arrays that the name of it gets from a list. I try but I can not create it. for example, I have this list: k=["one","two","three"] I want to create three arrays that the name of each array equal element of the list. that is mean:

one=np.array()

two=np.array()

three=np.array()

This is my code:

import numpy as np



k=["one","two","three"]
for i in range(0,len(k)):
    # print (k[i])
    j=str(k[i])+str(i)
    print(j)
    j=np.array("1")
  • It's a very bad idea to use strings to dynamically create loose variable names. How is the rest of the code going to know what they are? What if one of the names matches an existing variable? Attach them to a dict or use a multidimensional list. See [xy problbem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) -- what are you really trying to accomplish here? – ggorlen Aug 13 '21 at 05:37
  • Why not just make one Numpy array with an extra dimension, and index on that dimension? – Karl Knechtel Aug 13 '21 at 06:31

2 Answers2

1

you can use dictionary comprehension:

import numpy as np


k=["one","two","three"]
np_arrays = {name:np.array("1") for name in k}

then you can access each array like this: np_arrays['one']

Daniel
  • 1,895
  • 9
  • 20
0

What you can do is to create a dictionary that stores the each array inside a key which name corresponds to the list that you have.

import numpy as np

dict_arrays = {}
k=["one","two","three"]
for i in range(0,len(k)):
    j=str(k[i])+str(i)
    dict_arrays[k[i]]=np.array("1")
    
dict_arrays['one']

This solution is not creating an object for each value, however the dictionary allows you to work in that manner referencing the array by the index name.

GabrielP
  • 777
  • 4
  • 8