简体   繁体   English

在Pythonic while循环中执行迭代名称/变量的替代方法

[英]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. 所以我知道在迭代它时修改变量名是一种pythonic异端,但我一直在寻找一种好的pythonic方法来做到这一点并且可以解决它。 In statistical programming (Stata, SAS), code like this is common: 在统计编程(Stata,SAS)中,这样的代码很常见:

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

and this would give you y variables, a1,a2,a3....ay all equal to 0. 这会给你y变量,a1,a2,a3 .... ay都等于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. 特别是在下面的例子中(这是执行简单行 - 梯形缩减的代码的开头),我想用ax创建迭代变量(参见倒数第二行),其中x等于0(所以a0)在第一次迭代,第二次迭代时为1(或a1),依此类推,一直到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? 有人可以解释一个pythonic的方式来做我在这里用倒数第二行的ax变量做的事吗? And (imaginary) bonus points if you can explain it in a way that makes sense given the first example (from stata) :) 如果你能以一种有意义的方式解释它给出第一个例子(来自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] 您可以使用列表推导生成(x)= 0,对于[0,y]中的x

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 . 第二个例子令人困惑, ax在定义之前被引用,而a被称为函数而不是像listsp.array那样被索引。

Maybe look at reduced row echelon form in python from rosetta code . 也许从rosetta代码看python中减少的行梯形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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