Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在循环中动态分配变量_Python_Variables_Loops_Python 3.x - Fatal编程技术网

Python 在循环中动态分配变量

Python 在循环中动态分配变量,python,variables,loops,python-3.x,Python,Variables,Loops,Python 3.x,我需要给a到Z的变量分配一个数字列表。但是,这个列表的长度会有所不同。在一个循环中是否有这样做的方法? 到目前为止,我已经: file=open('inputfile.txt') data=file.readlines() vardict={1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14

我需要给a到Z的变量分配一个数字列表。但是,这个列表的长度会有所不同。在一个循环中是否有这样做的方法? 到目前为止,我已经:

file=open('inputfile.txt')
data=file.readlines()

vardict={1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F',
         7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L',
         13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q',
         18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V',
         23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}

for line in data:
    if line[0:1]=='V': #v is a marker that this line needs to assign variables. 
        num=1
        var=line.split() 
        var=var[1:] #remove the tag 
        for entry in var:
            x=vardict[num] #this will assign x to the correct variable
                           #need some lines here to create a variable from whatever is in x 
            num+=1 
例如,var=['16','17','13','11','5','3']需要分配给变量A到F。 我需要在以后的计算中大量使用这些变量,所以没有什么太麻烦的

编辑:我需要在计算中使用变量,直到出现另一行带有标记V的行,这时我需要将以下列表分配给变量A-Z,并在以后的计算中使用新变量

输入将采用以下形式:

V 1 -2 3 4 5 7 8 9 10
I (A+B)-C*F
I C*F-(A+B)    
R -+AB*CF
V 16 17 13 11 5 3 
O AB+C-D*E/F^

其中,其他行是要进行的各种计算

字符串中命名的变量可以通过写入全局字典进行赋值:

varname="A"
globals()[varname] = 16   # equivalent to A = 16
您可以通过列表
var
,生成字符串“A”、“B”。。。然后依次分配给每一个人

但这种欺骗行为可能是你做错了事情的一个迹象:它不那么明确,如果你的信用完了会发生什么

(参考)

如果创建一个对象来保存变量,则可以使用setattr函数。。。例如:

class variables():
    pass

vars = variables()

for line in data:
    if line[0:1]=='V': #v is a marker that this line needs to assign variables. 
        num=1
        v=line.split() 
        v=v[1:] #remove the tag 
        for entry in var:
            setattr(vars, vardict[num], entry) #creates vars.A=16 for example
            num+=1 

我错过什么了吗?这就是数组(Python中的列表或字典)的用途。为什么不想有一个变量列表,由字母“a”到“Z”索引?如果你坚持,你也许可以用
eval
做你想做的事,但那会很难看……你希望实现什么?您如何使用
x
?你在储存它们吗?现在,您只需将
vardict[var的最后一个条目]
赋值给
x
。您知道您可以对文件中的行执行
?我只需要一种方法将列表中的值赋值给变量a到Z。我唯一的问题是如何对大小不同的列表执行此操作。您将使用它们做什么?
import string
my_input = "V 1 -2 3 4 5 7 8 9 10"
doctored_input = map(int,my_input.split()[1:])

print dict(zip(string.ascii_uppercase,doctored_input))
#result : {'A': 1, 'C': 3, 'B': -2, 'E': 5, 'D': 4, 'G': 8, 'F': 7, 'I': 10, 'H': 9}