2017-05-06 88 views
1

我遇到了一些Python问题。我创建了一个Python代码,可以从文件中搜索和收集值,并将它们放在一个数组中,以便稍后操作:包括写入文件,绘图或执行一些计算。该文件如下:将代码从文件转换为数组的Python代码

file 1 (text file) 
    a = 1.2 
    a = 2.2 
    a = 6.5 

file 2 (text file) 
    b = 1.0 E-5 
    b = 2.5 E-4 

其中数组是

a_array = [1.2, 2.2, 6.5] 
    b_array = [1.0e-5, 2.5e-4] 

我想创建的a值的数组并为b值的数组。我写了这以下的代码file_1

a_array = [] 
for line in open (file_1): # it's a text file, was having issue with the format on this site 
    if line.startswith("a ="): 
    a = line[3:] # this to print from the 3rd value 
    print a 
    a_array.append(a)  
    print a_array 

它打印出以下几点:

['1.2'] 
['1.2', '2.2'] 
['1.2', '2.2', '6.5'] 

第三行是正是我想要的,但不是其他两行。

+2

这是因为你有内循环'print'命令。还要注意,你有一个'list',而不是'numpy.array',并且你有'str'数据类型,而不是'float',所以即使最后一行不是_exactly_你想要的。 – Michael

+1

我觉得你需要学习一些编程基础知识。现在就离开这个项目,首先创建更简单的东西。 – Olian04

+0

缩进是问题:P在我的评论后花了一段时间才注意到它。非常感谢你。编程是一个持续的学习之旅;我是python的新手。 – PythonNoob

回答

0

迈克尔是在评论是正确的,你有for循环内的print命令,所以它显示每个循环,但到了最后,a_arraÿ将只有最后显示的数值。

更有趣的问题是如何从你的第三行(['1.2', '2.2', '6.5'],字符串列表)到你想要的(a_array = [1.2, 2.2, 6.5],一个数字列表)。

如果你知道它们都是数字,你可以使用a_array.append(float(a)),但是这会遇到b的问题,使用科学记数法。幸运的是,Python可以转录科学记数法,如b,但没有空格。为此,您可以使用replace在转换之前删除所有空格。不要紧,如果没有空间,因此这种方法适用于a以及(用Python编写的3.5.2):

a_array = [] 
b_array = [] 
for line in open (file_1): # didn't correct formatting for opening text file 
    if line.startswith("a="):   
     a=line[3:] #this to print from the 3rd value 
     a_array.append(float(a.replace(' ','')))  
    elif line.startswith("b="): 
     b=line[3:] 
     b_array.append(float(b.replace(' ',''))) 
+0

感谢您的协助。我花了一段时间才注意到缩进是我的问题。谢谢 :) – PythonNoob