我对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'] 第三行正是我想要的,但其他两行不是。
发布于 2017-05-07 00:20:40
Michael的注释是正确的,您在for循环中使用了print命令,因此它会显示每个循环,但在最后,a_array将只是最终显示的值。
更有趣的问题是如何从第三行(['1.2', '2.2', '6.5'],字符串列表)获取所需内容(a_array = [1.2, 2.2, 6.5],数字列表)。
如果你知道它们都是数字,你可以使用a_array.append(float(a)),但这在b中遇到了问题,使用科学记数法。幸运的是,Python可以像b一样转录科学符号,但没有空格。为此,您可以在转换之前使用replace删除所有空格。如果没有空格也没关系,所以这个方法也适用于a (用Python3.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(' ','')))https://stackoverflow.com/questions/43822286
复制相似问题