0

I want to dynamically create arrays with variable names from another array. Say that I have:

    Array1 = ['a', 'b', 'c']

I want to now programatically create a new array for each value in Array1 (where I do not know how many values will actually be in Array1 and I do not know the names that will be in there) using the names provided in Array1. So effectively it will give me:

    a = []
    b = []
    c = []
4
  • Foreach over master array, and for each element create new array? Commented Jun 13, 2016 at 20:27
  • That is correct, and each new array should take the name that is given in the master array. Commented Jun 13, 2016 at 20:31
  • I'm not sure you can dynamically create individual variables like that in python. I defer to greater experts on that. As a compromise and perhaps something more readable create an dictionary of arrays with a, b, c as the keys in the dictionary. Commented Jun 13, 2016 at 20:32
  • technically you can do "dynamic variable names" by using dictionary operations on globals() but 99.8% of the cases you would do that it would make more sense to just define your own dictionary. (the only exception I can think of is when you want to monkey patch your code) Commented Jun 13, 2016 at 20:33

2 Answers 2

4

When you do Array1 = [a,b,c], you lose any information about the names of the variables you used to instantiate the array, so I'll assume you meant Array1=['a','b','c']. In Python, we generally use a dictionary to solve issues related to this. Using a dictionary, we can have a mapping from 'a' to an empty list like so:

Array1 = ['a','b','c']
dicty = {}
for i in Array1:
    dicty[i] = []

If this doesn't help you solve your problem, please give me more information about what problem you are trying to solve.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that is what I intended, I will change my original question to include the single quotes in Array1=['a','b','c']... Thank you for your solution, this works.
Good work @Brian, addressing the confusion while still providing a solution to the problem :) +1
0

So there are a few hypotheses that must be satisfied. Mainly, if Array1 has multiple entries that are equal, then you can't have different arrays for them--for example, if a == b evaluates to True, then you must assign them both the same arrays. Secondly, why not just keep a dictionary with the names of the corresponding arrays:

names_dict = {} ## names_dict[a] = (0,0), names_dict[b] = (1,0), ...
new_arrays = {}
for i in Array1.shape()[0]: 
    for j in Array1.shape()[1]:
         names_dict[Array1[i][j]] = (i,j)
         new_arrays[(i,j)] = np.array(...) ## whatever array you want to create goes in the "..." 

new_arrays[names_dict[a]] will evaluate to the array for element a

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.