-1

I am trying to create the following syntax using a for loop:

file_1_0 = data[0][0]
file_1_1 = data[0][1]
file_1_2 = data[0][2]
file_1_3 = data[0][3]
file_1_4 = data[0][4]
file_1_2 = "{:,}".format(file_1_2)
file_2_0 = data[1][0]
file_2_1 = data[1][1]
file_2_2 = data[1][2]
file_2_3 = data[1][3]
file_2_4 = data[1][4]
file_2_2 = "{:,}".format(file_2_2)

Given below is the for loop that I tried to achieve the above:

for i in range(1, len(file_data)):
    for k in range(0, len(file_data) - 1):
        for j in range(0, 4):
            str(file_) + str(i) + str(_) + str(j) = str(locals()["data_" + str(k) + "_" + str(j)])

I get an error

SyntaxError: can't assign to operator
hello kee
  • 289
  • 2
  • 6
  • 17
  • Do you mean... str(file_) + str(i) + str(_) + str(j) + "=" + str(locals()["data_" + str(k) + "_" + str(j)]) ....? – Ymareth Feb 11 '19 at 14:07
  • Also your script doesn't print anything out so even if you fix the error it won't "do" anything. – Ymareth Feb 11 '19 at 14:08
  • Do you have a full stack trace showing, for example, the line number the error occurs on? It would really help, considering that we don't have your dataset that you used to create the program. – nhubbard Feb 11 '19 at 14:10

1 Answers1

0

You can't assign to the expression str(file_) + str(i) + str(_) + str(j) - that's just a concatenation of four strings.

Unlike PHP and some other languages, Python doesn't have a way to turn a string expression into a variable name. If you really need it, you can generate your code and then use exec() to run it (that's Python's equivalent of eval(), while eval() in Python evaluates a single expression rather than multiple statements). But as you probably know, no solution that requires eval() is ever a good idea.

A better solution here would be to use dictionary keys instead of variables:

vars = {}
for i in range(1, len(file_data)):
    for k in range(0, len(file_data) - 1):
        for j in range(0, 4):
            vars[str(file_) + str(i) + str(_) + str(j)] = str(locals()["data_" + str(k) + "_" + str(j)])
Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
  • 1
    You can't use `eval()` to assign, because `eval()` only executes expressions. Assignments are statements. You'd have to use `exec()`, and that can't assign not local names in functions. Using the `globals()` dictionary lets you assign to global names too, but creating your own namespace dictionary is *far, far preferable*. – Martijn Pieters Feb 11 '19 at 14:17