如何将数组元素用作其余数据的变量名?

时间:2012-12-18 17:34:24

标签: python string variables matrix

我正在尝试将数据矩阵中的顶部条目(字符串)作为每列中其余(数字)数据的变量名称。我已经使用以下内容打开文件并创建矩阵。

with open('x.dat', 'r') as f:
    row = 0
    for line in f:
        words = line.split(',')
        for col in range(len(words)):
            DataMatrix[row][col] = words[col] 
        row += 1
f.close()

但是,我无法看到如何获取字符串并将其识别为数据“列表”的变量名称,该列表将由数字列填充。这比我做的要简单得多。有什么帮助吗?

数据文件如下所示:...(似乎无法正确显示格式,但每个[]是一行,行彼此堆叠在一起)
    ['%Time','FrameNo','Version','X','Y','Z',...]     [ '66266.265514', '948780', '2.5', '64', '0', '30' ...]     [66266.298785','948785',2.5','63','0','32',...]      ...

2 个答案:

答案 0 :(得分:1)

您正在寻找的是python的vars内置函数。这将为您提供表示范围内变量的dict

我没有按照你的例子中的代码来添加这个解决方案,但这里有一个使用vars的例子可能会有所帮助:

# Set up some data (which would actually be read from a file in your example)
headers = ['item', 'quantity', 'cost']
data = [['dress', 'purse', 'puppy'], [1, 2, 15], [27.00, 15.00, 2.00]]

for i in range(len(headers)):
  name = headers[i]
  value = list()
  for data_item in data[i]:
    value.append(data_item)
  # This sets the name of the header to the name of a variable
  vars()[name] = value

# Print to prove that vars() worked
print 'Items', item
print 'Quantities', quantity
print 'Costs', cost

产生以下输出:

Items ['dress', 'purse', 'puppy']
Quantities [1, 2, 15]
Costs [27.0, 15.0, 2.0]

答案 1 :(得分:0)

使用int功能

with open('x.dat', 'r') as f:
    row = 0
    for line in f:
        words = line.split(',')
        for col in range(len(words)):
            DataMatrix[row][int(col)] = words[int(col)] 
        row += 1
f.close()

或者,您可以执行CSV reader以简化此操作。

with open('x.dat', 'rb') as csvfile:
    theReader = csv.reader(csvfile, delimiter=',')
    row=0;
    for line in theReader:
        row+=1
        for col in range(len(line)):
             DataMatrix[row][int(col)] = words[int(col)]