Search code examples
pythonloopsvariable-assignmentalphabet

Cycle through letters of the alphabet in a loop and assign values to them in Python?


Here the number of variables (which correspond to numfactors) are assigned manually to each letter of the alphabet. So the first variable is A and it gets assigned the value of an array slice (paths[0:35] for example). B is set to paths[35:70], repeat until the end. Now I could just make a very ugly if-then sequence for each possible letter, but it seems there has to be a better way. Current method:

import numpy as np
numfactors = 4
curvelen = 35
paths = np.random.randn(140)

indexes = list()
for i in range(numfactors):
    indexes.append("paths[" + str(curvelen*i) + ":" + str(curvelen*(i+1)) + "]")

A=eval(indexes[0])
B=eval(indexes[1])
C=eval(indexes[2])
D=eval(indexes[3])

Okay that's hardcoded, and 4 values are expected A, B, C, D. But the actual number could be 1 to 20 for example. Something like this:

for i in range(indexes):
# loop 1
   A=eval(indexes[i])
# loop 2
   B=eval(indexes[i])
# loop 3
   C=eval(indexes[i])
# ... to end

I think that summarizes the problem. Each loop goes through A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P etc. and assigns the letter-variable value to indexes[i] which is evaluated as a NumPy array slice. Any help is appreciated!

Update: thanks to @Diego Torres Milano and the linked post, this is all done in a few lines of code:

import string
import numpy as np

numfactors = 4
curvelen = 35
paths = np.random.randn(140)

# create path indexing for each input curve
indexes = list()
for i in range(numfactors):
    indexes.append("paths[" + str(curvelen*i) + ":" + str(curvelen*(i+1)) + "]")

# make a dictionary from A to Z for variables
variables = dict(zip(string.ascii_uppercase, indexes))

# assign each key name as variables (A-Z) to the paths defined prior
for k, v in variables.items():
    exec(f"{k} = {v}")

NOTE: I know using exec() and eval() are not safe. I actually have a great parser from here: https://blog.oyam.dev/python-formulas/ that I pass the (simplified) formulas to before evaluating them with exec(), so they are cleared as "okay" before the unsafe statements run.


Solution

  • You can create a dictionary with uppercase letters as key using

    import string
    dict(zip(string.ascii_uppercase, indexes))