我遇到了一些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']
第三行是正是我想要的,但不是其他两行。
这是因为你有内循环'print'命令。还要注意,你有一个'list',而不是'numpy.array',并且你有'str'数据类型,而不是'float',所以即使最后一行不是_exactly_你想要的。 – Michael
我觉得你需要学习一些编程基础知识。现在就离开这个项目,首先创建更简单的东西。 – Olian04
缩进是问题:P在我的评论后花了一段时间才注意到它。非常感谢你。编程是一个持续的学习之旅;我是python的新手。 – PythonNoob