Ryflex
Ryflex

Reputation: 5769

For loop creating dynamic strings?

Anyone know what I'm doing wrong in the code below?

ZeroList = ["53", "52", "24", "26", "36", "37", "40", "41", "43", "44", "45"]

for ZeroID in ZeroList:
    if row[ZeroID]:
        R+str(ZeroID) = float(row[ZeroID])
    else:
        R+ZeroID = 0

Doing the following output:

print R53
print R52
print R24

Would output:

2392.118329
232.298323
142.521513

I've tried several options to try and create the dynamic string, in the above example there are two ways that I've tried.

Any ideas?

EDIT

        ZeroList = {"R53": "", "R52": "", "R24": "", "R26": "", "R36": "", "R37": "", "R40": "", "R41": "", "R43": "", "R44": "", "R45": ""}

        for ZeroID in ZeroList:
            if row[int(ZeroID[-2:])]:
                ZeroList[ZeroID] = float(row[int(ZeroID[-2:])])
            else:
                ZeroList[RZeroID] = 0

        datatoapp = [row[0], row[1], row[8], row[9], '{0:0.2f}'.format(float(ZeroList[R52]))]

Upvotes: 0

Views: 1010

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121466

Keep your data out of your variable names.

Use a dictionary to store your items, creating dynamic keys instead:

results = {}

for ZeroID in ZeroList:
    if row[ZeroID]:
        results[R+str(ZeroID)] = float(row[ZeroID])
    else:
        results[R+str(ZeroID)] = 0

Upvotes: 5

Related Questions