2013-10-09 61 views
-2

我在Python 3.3.2中工作。現在我正在嘗試從txt文件創建列表的列表。例如:如何從txt文件創建列表的列表

我有這個數據的txt文件:

361263.236 1065865.816 
361270.699 1065807.970 
361280.158 1065757.748 
361313.821 1065761.301 

我想Python來生成這個txt文件列表的列表,所以我需要的數據是這樣的:[[102547.879, 365478.456], [102547.658, 451658.263], [102658.878, 231456.454]]

我該做什麼?

感謝您的關注!

+2

這些文件可能對您有用:[讀寫文件](http://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files),[Lists ](http://docs.python.org/3/tutorial/introduction.html#lists),['str.split'](http://docs.python.org/3/library/stdtypes.html#str .split) – Kevin

+0

歡迎來到SO!如果您希望某人花費時間和精力回答您的問題,在提出問題之前展示您的時間和精力是一個不錯的主意。這涉及包括您嘗試過的方法,您聽過的方法但不瞭解如何使用方法,以及其他任何表明您在諮詢SO之前努力爲自己尋找解決方案的努力。 – Enigmadan

回答

0

這可能會做:

LofL = [] 
with open("path", "r") as txt: 
    while True: 
     try: 
      LofL.append(txt.readline().split(" ")) 
     except: 
      break 
+1

這是非常不習慣的Python。 – chepner

2

我會鼓勵使用新的程序員with聲明,這是一個好習慣進入。

def read_list(filename): 
    out = [] 
    # The `with` statement will close the opened file when you leave 
    # the indented block 
    with open(filename, 'r') as f: 
     # f can be iterated line by line 
     for line in f: 
      # str.split() with no arguments splits a string by 
      # whitespace charcters. 
      strings = line.split() 
      # You then need to cast/turn the strings into floating 
      # point numbers. 
      floats = [float(s) for s in strings] 
      out.append(floats) 
    return out 

根據文件的大小,你也可以代替使用out列表,修改它使用yield關鍵字。

1
with open("data.txt","r") as fh: 
    data = [ [float(x), float(y)] for x,y in line.split() for line in fh ] 

這是的情況下,我認爲map更具有可讀性,雖然具有包裝,在一個呼叫到list在Python 3.x的從它有損。

data = [ list(map(float, line.split())) for line in fh ] 
+1

或者只是'[[float(el)for row.split()] for fh中的行]'來模擬2.x風格的'map(float,...) –