0

我试图让数据矩阵中的顶部条目(字符串)成为每列中其余(数字)数据的变量名。我使用以下内容打开文件并创建矩阵。

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', '版本','X','Y','Z',...] ['66266.265514','948780','2.5','64','0','30'...] [66266.298785','948785 ', 2.5','63','0','32',...] ...</p>

4

2 回答 2

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]
于 2012-12-18T20:48:18.943 回答
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 阅读器来稍微简化此操作。

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)] 
于 2012-12-18T17:36:29.903 回答