2013-04-13 23 views
-1

我有一個輸入文件:如何將文件中的特定行添加到Python中的List?

3 
PPP 
TTT 
QPQ 

TQT 
QTT 
PQP 

QQQ 
TXT 
PRP 

我想讀這個文件和組這些案件到合適的boards。 要閱讀Count(無板)。我有代碼:

board = [] 
count =''  
def readcount(): 
     fp = open("input.txt") 
     for i, line in enumerate(fp): 
      if i == 0: 
       count = int(line) 
       break 
     fp.close() 

但是我沒有怎麼這些塊解析成List中的任何想法:

TQT 
QTT 
PQP 

我試着用

def readboard(): 
    fp = open('input.txt') 
    for c in (1, count): # To Run loop to total no. of boards available 
     for k in (c+1, c+3): #To group the boards into board[] 
      board[c].append(fp.readlines) 

但它錯了。我知道列表的基本知識,但在這裏我無法解析文件。

這些板子是在2到4,6到8等等。如何讓他們進入Lists? 我想解析這些到CountBoards,以便我可以進一步處理它們?

請建議

+0

什麼是3?是每個塊的項目數量還是塊的數量? – mgilson

+0

更新問題。 3或(計數)是否定的。任何文件中的板子 – Man8Blue

回答

1

我不知道如果我理解你想要的結果。我想你想要一個列表清單。 假設你想讓電路板成爲: [[數據,數據,數據],[數據,數據,數據],[數據,數據,數據]],那麼你需要定義如何解析輸入文件。 。特別是:

  • 1行計數數
  • 數據被每行
  • 板由空格分隔輸入。

如果是這樣的話,這應該正確解析您的文件:

board = [] 
count = 0 
currentBoard = 0 

fp = open('input.txt') 
for i,line in enumerate(fp.readlines()): 
    if i == 0: 
     count = int(i) 
     board.append([]) 
    else: 
     if len(line[:-1]) == 0: 
      currentBoard += 1 
      board.append([]) 
     else: #this has board data 
      board[currentBoard].append(line[:-1]) 
fp.close() 
import pprint 
pprint.pprint(board) 

如果我的假設是錯誤的,那麼這可以被修改,以適應。 個人而言,我會使用字典(或命令字典),並從len(板)得到計數:

from collections import OrderedDict 
currentBoard = 0 
board = {} 
board[currentBoard] = [] 

fp = open('input.txt') 
lines = fp.readlines() 
fp.close() 

for line in lines[1:]: 
    if len(line[:-1]) == 0: 
     currentBoard += 1 
     board[currentBoard] = [] 
    else: 
     board[currentBoard].append(line[:-1]) 

count = len(board) 
print(count) 
import pprint 
pprint.pprint(board) 
+0

上面的代碼對我來說工作得很好,那就是我想要的。但現在要訪問董事會的任何元素說第二板第二線和第三元素,我正在使用「打印列表(板[1])[1] [2]」是好嗎?或者有什麼方法可以在董事會級別訪問? – Man8Blue

+0

我不確定電路板級別的含義。您可以像上面提到的那樣訪問電路板數據(電路板[1] [1] [2]),或者訪問電路板的字符(電路板[1] [1]),或者訪問電路板的元件(電路板[1 ])。這取決於你的目標是什麼。如果這些數據表示某種特定的東西,那麼類可能會比一組數組陣列更直觀。 – tstone2077

0

如果你只是想採取具體的行號,並把它們放入一個列表:

line_nums = [3, 4, 5, 1] 
fp = open('input.txt') 
[line if i in line_nums for i, line in enumerate(fp)] 
fp.close() 
相關問題