从文件读取数据到二维数组[Python]

时间:2016-11-30 03:35:28

标签: python multidimensional-array

我有一个像这样的文件.txt:

8.3713312149,0.806817531586,0.979428482338,0.20179159543
5.00263547897,2.33208847046,0.55745770379,0.830205341157
0.0087910592556,4.98708152771,0.56425779093,0.825598658777

我想将数据保存在二维数组中,例如

array = [[8.3713312149,0.806817531586,0.979428482338,0.20179159543],[5.00263547897,2.33208847046,0.55745770379,0.830205341157],[0.0087910592556,4.98708152771,0.56425779093,0.825598658777]

我尝试使用此代码

#!/usr/bin/env python

checkpoints_from_file[][]

def read_checkpoints():
    global checkpoints_from_file
    with open("checkpoints.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            checkpoints_from_file.append(line.split(","))
        print checkpoints_from_file


if __name__ == '__main__':
    read_checkpoints()

但它不起作用。 你们能告诉我如何解决这个问题吗?谢谢

2 个答案:

答案 0 :(得分:1)

从您的文件中读取,

def read_checkpoints():
    checkpoints_from_file = []
    with open("checkpoints.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            checkpoints_from_file.append(line.split(","))
        print(checkpoints_from_file)


if __name__ == '__main__':
    read_checkpoints()

<小时/> 或者假设您可以使用字符串文字

成功读取此数据
lines = """8.3713312149,0.806817531586,0.979428482338,0.20179159543
5.00263547897,2.33208847046,0.55745770379,0.830205341157
0.0087910592556,4.98708152771,0.56425779093,0.825598658777"""

和列表理解,

list_ = [[decimal for decimal in line.split(",")] for line in lines.split("\n")]

扩展,

checkpoints_from_file = []
for line in lines.split("\n"):
    list_of_decimals = []
    for decimal in line.split(","):
        list_of_decimals.append(decimal)
    checkpoints_from_file.append(list_of_decimals)

print(checkpoints_from_file)

您的错误:

  1. 与某些语言不同,在Python中,您不需要初始化类似checkpoints_from_file[][]的列表,而是可以初始化一维列表checkpoint_from_file = []。然后,您可以使用Python list.append()
  2. 在其中插入更多列表

答案 1 :(得分:1)

您的代码中有两个错误。第一个是.equals(b)不是在Python中初始化多维数组的有效方法。相反,你应该写

checkpoints_from_file[][]

这会初始化一维数组,然后在循环中将数组附加到其中,从而创建包含数据的2D数组。

您还将数组中的条目存储为字符串,但您可能希望将它们作为浮点数存储。您可以使用float函数以及list comprehension来完成此操作。

checkpoints_from_file = []