2016-12-13 92 views
2

我一直堅持這個近3天,我已經嘗試了很多不同的方式,但他們都沒有工作!如何從txt文件製作3D列表?蟒蛇

TXT文件(num.txt)看起來像:

1234 
4321 
3214 
3321 
4421 
2341 

我怎樣才能把這個文件放到由2行3列的3D名單?

我想實現的輸出是:

[ [['1','2','3','4']['4','3','2','1']['3','2','1','4']], [['3','3','2','1']['4','4','2','1']['2','3','4','1']] ] 

(我已經分開出來,試圖多一點,使其更容易看到!)

我認爲這將是類似於製作2D列表,但沒有任何我嘗試過的!任何人都可以幫忙嗎?

謝謝!

回答

1

你要打開的文件和類型,投行的每個字符串list,如:

my_list = [] 
sublist_size = 3 

with open('/path/to/num.txt') as f: 
    file_lines = list(f) 
    for i in range(0, len(file_lines), sublist_size): 
     my_list.append([list(line.rstrip()) for line in file_lines[i:i+sublist_size]]) 
     #       ^Remove `\n` from right of each line 

這裏my_list將持有你想要的值:

[[['1','2','3','4']['4','3','2','1']['3','2','1','4']], 
[['3','3','2','1']['4','4','2','1']['2','3','4','1']]] 
+0

不要忘了'.strip()''的'\ n''從結束每個'行' – jez

+0

不,至少對於我在Python 2.7中,每行都包含換行符 – jez

+0

是的,我的不好。更新答案。感謝您指出 –

2

這裏是一個非常簡單的方法用一些簡單的算術來做:

with open('num.txt') as infile: # open file 
    answer = [] 
    for i,line in enumerate(infile): # get the line number (starting at 0) and the actual line 
     if not i%3: answer.append([]) 
     answer[-1].append(list(line.strip())) 
+1

值得一提的是,對於足夠大的文件,這種方法幾乎是強制性的,因爲它不需要將整個文件加載到內存中。 – TemporalWolf

+0

@TemporalWolf:這是有爭議的,除非你想讓一個生成器產生每行三行,因爲'answer'增長以保存整個文件。如果OP確實需要文件行的三元組列表,那麼它可能會幫助(非常輕微地)使用元組而不是列表,在'answer'內保存空間 – inspectorG4dget

+0

其他答案**要求在加載之前加載整個文件在上面**。您的解決方案可用於定期保存結果,從而處理無法完全保存在內存中的文件。這使用了兩個迭代器和python的智能文件緩衝區。 – TemporalWolf

1

使用range()功能和簡單的列表理解

with open('./text_files/num.txt', 'r') as fh: # change to your current file path 
    l = [list(l.strip()) for l in fh] 

n = 3 # chunk size 
result = [l[i:i + n] for i in range(0, len(l), n)] # splitting into chunks of size 3 
print(result) 

輸出:

[[['1', '2', '3', '4'], ['4', '3', '2', '1'], ['3', '2', '1', '4']], [['3', '3', '2', '1'], ['4', '4', '2', '1'], ['2', '3', '4', '1']]] 
+0

[.readlines()](http://stupidpythonideas.blogspot.com/2013/06/readlines-considered-silly.html)不是必需的,因爲它會讀取整個文件並在返回之前對其進行解析。 fh中的l返回一個根據需要返回行的迭代器。 – TemporalWolf

+0

@TemporalWolf,好的,刪除了。感謝提示 – RomanPerekhrest

0

我認爲這是更清晰,不需要將整個文件加載到內存中的另一種選擇:

inner_size = 3 
inner_range = range(inner_size) # precompute this since we'll be using it a lot 
with open('/home/user/nums.txt') as f: 
    result = [] 
    try: 
     while True: 
      subarr = [] 
      for _ in inner_range: 
       subarr.append(list(f.next().rstrip())) 
      result.append(subarr) 
    except StopIteration: 
     pass 

在文件對象上使用內置__iter__,我們構建子數組並將它們追加到結果數組,並使用StopIteration異常來了解我們已完成,並丟棄任何額外的數據。如果您想在最後保留任何部分子表格,您可以輕鬆地將if subarr: result.append(subarr)作爲例外。

寫成一個列表理解(儘管沒有收回任何最終,部分子列表的能力):

inner_size = 3 
inner_range = range(inner_size) 
with open('/home/user/nums.txt') as f: 
    result = [] 
    try: 
     while True: 
      result.append([list(f.next().rstrip()) for _ in inner_range]) 
    except StopIteration: 
     pass