繁体   English   中英

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

[英]How can an element of an array be used as a variable name for some of the rest of the data?

我正在尝试获取数据矩阵中的顶部条目(字符串),作为每一列中其余(数字)数据的变量名。 我用以下方法打开文件并创建矩阵。

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',...]…

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

我没有充分遵循示例中的代码来向其中添加此解决方案,但是下面是一个使用var的示例,该示例可能会有所帮助:

# 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]

使用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)] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM