在Python中的循环中创建和使用多个变量 [英] Create and use multiple variables in a loop in Python

查看:423
本文介绍了在Python中的循环中创建和使用多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Python编写一个循环,该循环创建变量,并且还使用创建的尚未创建的变量来生成线性方程组.这是到目前为止我得到的:

I'm trying to write a loop in Python that creates variables and also uses created an not-yet-created variables to produce a system of linear equations. This is what I've got so far:

P=[[0, 0, 0, 0.5, 0, 0.5],
[0.1, 0.1, 0, 0.4, 0, 0.4],
[0, 0.2, 0.2, 0.3, 0, 0.3],
[0, 0, 0.3, 0.5, 0, 0.2],
[0, 0, 0, 0.4, 0.6, 0],
[0, 0, 0, 0, 0.4, 0.6]]

for j in range(6):
    globals()['x%s' % j] = 0
    for i in range(6):
        globals()['x%s' % j] += P[i][j]*globals()['x%s' % i]

但是由于最后一行,我得到了KeyError输出.我猜是因为还没有定义第二个变量(globals()['x%s' % i]),但是我不知道如何在稍后要定义它们时使用等号右边的变量.

but I get a KeyError output because of the last line. I guess it's because the second variable ( globals()['x%s' % i]) is not defined yet but I don't know how to use the variables to the right of the equals sign when they are going to be defined later.

推荐答案

首先,不要不要为此使用globals()(或者实际上几乎不使用).创建自己的字典以存储您动态创建的值:

First of all, do not use globals() for this (or in fact almost never); create your own dictionary to store your dynamically created values:

vars = {}
vars['blabla'] = 123

尽管得到KeyError的原因是,您试图从globals()读取不存在的变量(但这也将与自定义字典一起发生).这行:

The reason you are getting the KeyError though is that you're trying to read a variable from globals() that doesn't exist (but this would also happen with a custom dict). This line:

globals()['x%s' % j] += P[i][j]*globals()['x%s' % i]

实际上是以下简称:

globals()['x%s' % j] = globals()['x%s' % j] + P[i][j]*globals()['x%s' % i]

但尚未定义globals()['x%s' % j].因此,您正在尝试向不存在的内容中添加内容.

but globals()['x%s' % j] is not defined yet. So you're trying to add something to something that doesn't exist.

相反,在执行+=操作之前,您需要执行以下操作:

Instead, you need to do something like the following before you do the += operation:

if 'x%s' % j not in globals():
    globals()['x%s' % j] = 0

但是,如果正确执行并使用dict和其他一些增强功能,它将看起来像这样:

BUT, if you do it properly and use a dict, and some other enhancements, it would look like this:

# it's nicer to use floats uniformly, not a mix of ints and floats;
# it's also safer because in Python 2.x, int divided by float will yield a floored down int
P = [[0.0, 0.0, 0.0, 0.5, 0.0, 0.5],
     [0.1, 0.1, 0.0, 0.4, 0.0, 0.4],
     [0.0, 0.2, 0.2, 0.3, 0.0, 0.3],
     [0.0, 0.0, 0.3, 0.5, 0.0, 0.2],
     [0.0, 0.0, 0.0, 0.4, 0.6, 0.0],
     [0.0, 0.0, 0.0, 0.0, 0.4, 0.6]]

vars = {}

for j in range(len(P)):
    vars['x%s' % j] = 0
    for i in range(len(P[0])):
        vars.setdefault('x%s' % j, 0.0)  # shorthand for the `if` I described
        vars['x%s' % j] += P[i][j] * vars['x%s' % i]

此外,由于vars似乎最终只包含键x0x5,所以我宁愿使用list来代替

Also, since vars seems to end up just containing the keys x0 to x5, I would rather use a list instead;

X = [0] * len(P)  # creates [0, 0, 0, 0, 0, 0]
for j in range(len(P)):
    for i in range(len(P[0])):
        X[j] += P[i][j] * X[i]

这样,您甚至不需要setdefault调用.

This way, you don't even need the setdefault call.

但是请记住,我对您要实现的数学算法/计算并不熟悉,因此我也无法发现您的代码中存在任何非技术性的错误或缺点.

Keep in mind, though, that I'm not familiar with the mathematical algorithm/computation you're trying to implement, so I'm also not able to spot any non-technical bugs or shortcomings in your code.

这篇关于在Python中的循环中创建和使用多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆