Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array name

How can a generate multiple array with this syntax result0, result1, result2 etc..

I tried this and this work :

for i in xrange(0, 7):
        var_num = i
        globals()['result%s' % var_num] = []
        globals()['result%s' % var_num].append(1000+i)
        print ['result%s' % var_num][0]

it gives me theses array :

result0
result1
result2
result3
result4
result5
result6

But i'm sure there is another way to do that?...

Thanks

like image 222
Adeel ASIF Avatar asked Sep 16 '26 12:09

Adeel ASIF


2 Answers

How about using a dictionary.

>>> variables = {}
>>> for i in xrange(0, 7):
...     variables['result%s' % i] = [1000 + i]
...
>>> variables
{'result6': [1006], 'result4': [1004], 'result5': [1005], 'result2': [1002], 'result3': [1003], 'result0': [1000], 'result1': [1001]}
>>> variables['result2']
[1002]
>>> variables['result6']
[1006]
like image 119
falsetru Avatar answered Sep 19 '26 06:09

falsetru


Why do you want to have like that? Why not just an array of arrays? You will be able to iterate over the arrays easily when you keep them in another array.

like image 28
Bartosz Marcinkowski Avatar answered Sep 19 '26 05:09

Bartosz Marcinkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!