简体   繁体   中英

Alternate way to do Iterative name/variables in Pythonic while loop

So I know that it is a kind of pythonic heresy to modify a variable name while iterating over it but I have been searching for a good pythonic way to do this and can figure it out. In statistical programming (Stata, SAS), code like this is common:

for x in 1/y:
gen a`x'=0

and this would give you y variables, a1,a2,a3....ay all equal to 0.

I have seen other posts say that to do something like this you can create a library and call all of these values but what if you have an indefinite (finite) number of values?

In particular in the example below (which is the beginnings of a code to perform simple row-echelon reduction), I would like to create iterative variables (see the second-to-last line) with ax where x is equal to 0 (so a0) on the first iteration, 1 (or a1) on the second iteration and so on all the way up to ax.

I dont see a way to do this with dictionaries because I would have to specify the number of entries in it first. Maybe my understanding here is flawed but this is how I think of it.

def cmultadd(n, j, k, const):
    out = eye(n)
    out[j,k] = const
    return out  

def rowred(a):
    numrows = len(a)-1
    x=0
    while x<=numrows:
        ax=sp.dot(cmultadd(3,x,0,-ax[x+1,0]/ax[0,0]), a(x-1)); ax
        x=x+1

Can someone kindly explain a pythonic way to do what I am trying to do with the ax variable in the second to last line here? And (imaginary) bonus points if you can explain it in a way that makes sense given the first example (from stata) :)

Thanks.

For the first example,

 for x in 1/y: gen a`x'=0 

you can use list comprehension to generate a(x) = 0, for x in [0, y]

a = [0 for x in range(y)]

or call a function or some other math

a = [math.pow(x, 2) for x in range(y)]

The second example is confusing, ax is referenced before it is defined and a is called like a function instead of indexed like a list or sp.array .

Maybe look at reduced row echelon form in python from rosetta code .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM