Ask Your Question
0

create numpy arrays or lists with customiza names

asked 2013-07-09 05:28:47 -0500

mresimulator gravatar image

Hi experts!

Im running a script with a for-cycle. In every loop a list (or np array) is generated. I wanna these lists receive the name "list_number_###", where ### is the index of the for-cycle (e.g.: if the for-cycle is " for srange(a,b+1,1)..." i wanna that the np array or list receive the names "list_number_a", "list_number_a+1",..., "list_number_b".

How can i do that?

Waiting for your answers.

Thanks a lot!

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2013-07-09 13:21:56 -0500

tmonteil gravatar image

updated 2013-07-09 13:27:17 -0500

As explained by @Luca, it is not a good idea to have indices as a substring of the name of your lists, but as indices: list_number[i] makes more sense than list_number_i.

Lists indices go from 0 to length-1, so if a is big (or if the set of indices is sparse), you can use a dictionary instead. For example, assume that the i^th element (more precisely the element whose key is i) of your dictionary is the list [i,i^2], you can write:

sage: a = 10
sage: b = 20

sage: dict_number = {}
sage: for i in srange(a, b+1, 1):
....:     dict_number[i] = [i, i^2]

Then you can call the element of your dictionary whose key is 13:

sage: dict_number[13]
[13, 169]

Note that the keys of your dictionary can be more than just numbers, for example they can be strings:

sage: dict_number['plop'] = [12,13]
sage: dict_number['plop']          
[12, 13]

You can read more about python dictionaries here.

edit flag offensive delete link more
0

answered 2013-07-09 07:08:20 -0500

Luca gravatar image

Have you considered using lists of lists?

list_of_np = []
for i in range(10):
   list[i] = my_np_array()

or even, using list comprehensions,

list_of_np = [my_np_array() for i in range(10)]

If you are really determined to have dynamically generated variable names, Python allows you to modify the current module scope via the globals() call. You can do

for i in range(10):
  globals()["list_number_" + str(i)] = my_np_array()

However in my opinion you'd better stick with one of the two previous forms.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-07-09 05:28:47 -0500

Seen: 557 times

Last updated: Jul 09 '13