在循环中动态分配变量

2024-03-29 05:38:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要为从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,并在以后的计算中使用新变量。在

输入格式如下:

^{pr2}$

其他行是要进行的各种计算。在


Tags: thetoin列表fordataisvar
3条回答

如果你创建一个对象来保存你的变量,你可以使用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 
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}

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

varname="A"
globals()[varname] = 16   # equivalent to A = 16

您可以使用列表var,生成字符串“A”、“B”。。。依次分配给每个人。在

但这种诡计也许是你做错事情的一个信号:它不那么明确,如果你的字母用完了会怎么样?在

(参考) http://www.diveintopython.net/html_processing/locals_and_globals.html

相关问题 更多 >