2016-11-30 59 views
0

我有一個文件的.txt這樣的:從文件中讀取數據,以一個二維數組[Python的]

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

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

回答

1

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

checkpoints_from_file = [] 

這初始化一個一維數組,然後追加數組它在你的循環,這會爲您的數據的二維數組。

您還將條目作爲字符串存儲在數組中,但您可能希望它們作爲浮點數存在。您可以使用float函數以及list comprehension來完成此操作。

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

完美的工作,謝謝 – Pino

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