簡體   English   中英

從文件讀取數據到二維數組[Python]

[英]read data from file to a 2d array [Python]

我有一個像這樣的.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()

但它不起作用。 你們能告訴我如何解決嗎? 謝謝

從您的文件中讀取

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()


或者假設您可以使用字符串文字成功讀取此數據,

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)

展開,

 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()在其中插入更多列表。

您的代碼中有兩個錯誤。 首先是checkpoints_from_file[][]不是在Python中初始化多維數組的有效方法。 相反,您應該寫

checkpoints_from_file = [] 

這將初始化一維數組,然后在循環中向其附加數組,從而使用數據創建一個2D數組。

您也將條目作為字符串存儲在數組中,但是您可能希望它們為浮點型。 您可以使用float函數以及列表推導來完成此操作。

checkpoints_from_file.append([float(x) for x in line.split(",")])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM