Home > Back-end >  How can I specify each iteration in a for loop's output? Python
How can I specify each iteration in a for loop's output? Python

Time:08-05

I have a .json file with multiple values, seperated by commas. I would like to go through the file and output each value sequentially, as variables. The first one being x1, the second one being x2 and so on. The point is so that I can use these values in an equation later on. The output would look like this:

x1 = 0.0234
x2 = 0.512
x3 = 0.9782

I pretty sure I need to use a for loop after this:

g = open('beat_times_knownsong1.json')
another_song = json.load(g)

EDIT: this is some of the .json data:

0.023219954648526078,
    0.5108390022675737,
    0.9752380952380952,
    1.4628571428571429,
    1.9504761904761905,
    2.414875283446712,
    2.9024943310657596,
    3.3668934240362813,
    3.8545124716553287,
    4.31891156462585,
    4.806530612244898,
    5.270929705215419,
    5.758548752834467,
    6.222947845804988,
    6.710566893424036,
    7.174965986394557,

they're just numbers increasing in value. If I just do:

g = open('beat_times_knownsong1.json')
another_song = json.load(g)

for beat in another_song:
    print(beat)

then it just prints the values. I would like for it to save each value to an "x" variable, increasing from x1 = 0.023219954648526078 to x2, x3 and so on.

CodePudding user response:

  1. Use enumerate to get the index of the current value in the list you are iterating over.
  2. There are different ways in Python to convert a string to a variable (see e.g. here). One is using the locals method, which returns a dict that reflects all local variables defined in a scope (e.g. a function) and allows manipulating them (e.g. reassigning, adding new variables or deleting existing ones).

Example:

g = open('beat_times_knownsong1.json')
another_song = json.load(g)

for i, beat in enumerate(another_song):
    locals()[f"x{i}"] = beat

print(x0)
print(x1)
...

CodePudding user response:

Why not using a dictionary instead of variable:

g = open('beat_times_knownsong1.json')
another_song = json.load(g)
variable_dict={}
i=0
for beat in another_song:
    variable_dict["x" str(i)]=beat
    i =1

and you can get the value you want like this:

variable_dict["x1"]

  • Related