0

I have a simple code where I want to update the variable names as follows:

n = 5

for i in range(0, n):
    train_fold_[i], val_fold_[i] = result[i][0],result[i][1]

I want the above code to generate a total of 10 variables with names train_fold_0, val_fold_0, train_fold_1, val_fold_1,......, train_fold_4, val_fold_4.

However, when I run this code, it is only generating 2 variables as follows: train_fold_i, val_fold_i.

I know this is extremely simple, but can someone please help me out with this as I'm relatively new to python.

3
  • Usually you would use a data structure in this case (probably a list). Why do you want to have 10 different variables? Commented Mar 14, 2021 at 1:05
  • 1
    Do train_fold, val_fold = zip(*[result[i] for i in range(n)]). You can now access your ten values as train_fold[0], val_fold[0], train_fold[1], etc. Commented Mar 14, 2021 at 1:11
  • If n == len(result) you can do it more simply: train_fold, val_fold = zip(*result) Commented Mar 14, 2021 at 1:13

1 Answer 1

1

You could use exec

n = 5

for i in range(0, n):
    value1, value2 = i, i+1
    exec(f'train_fold_{i}, val_fold_{i} = {value1}, {value2}')

then

print(train_fold_3, val_fold_3)
>>> 3 4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.