Link to home
Start Free TrialLog in
Avatar of Europa MacDonald
Europa MacDonaldFlag for United Kingdom of Great Britain and Northern Ireland

asked on

entering variables into an array

I have 100 variables, var_1 to var_100

I have to transfer the content of each variable into each element of array b row 2 :  b[2]

var_1 to b[2,0]
var_2 to b[2,1] and so on

I got as far as this code
-------------------------------------
count = 0

for i in b[2]:
    if count < 100:
        b[2] = var_1
   
        count =+ 1
------------------------------------

what is the best way to do this ?

I am just learning python thankyou
Avatar of Norie
Norie

Where are these variables and their values coming from?
ASKER CERTIFIED SOLUTION
Avatar of Louis LIETAER
Louis LIETAER
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Europa MacDonald

ASKER

they are the results of calculations made on another array.
their values are data type float


Louis I am getting the error

b[2, i] = locals()[tmp]

ValueError: setting an array element with a sequence.
with my source code above ?
yes

the only thing I changed was 'var_' to 'result_' which is the prefix of my variables

Spyder 4.0.1
Python 3.7.6 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10

when I change this line
tmp = ('result_' + str(i+1)) to  tmp = ('result_' + str(i)) (which is good)

I get the error

 b[2, i] = locals()[tmp]

KeyError: 'result_0'
provide your code please, the one I copy/paste was tested on my Mac. In between, I will look about "locals()" on windows
is variable result_0 exists ?

yes

result_0 to result_100

could you print tmp variable just before error
it just prints result_0
then
b[2, i] = locals()[tmp]

KeyError: 'result_0'

-------------------------------
for i in range(sl):
    tmp = ('result_' + str(i))
    print(tmp)
    b[2, i] = locals()[tmp]
   
print(b[2])
what is the result of the print ? what is the value of variable "sl"
the result of the print is  result_0
the value of variable sl is 100 
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Try globals() function instead of  locals(), depending where you declare result_0..100
still same keyerror
can you provide entire code ?
I think I found : too much parenthesis.

tmp = 'result_' + str(i)