2016-02-29 82 views
0

我正在製作一個拉丁方形棋盤拼圖,我正在編寫代碼以打開文本文件並將數據存儲在字典中。但是,當我循環代碼時,它會重複打印出來。 例如我的文本文檔中,我有在字典中循環

ABC 
CAB 
BCA 

運行我的代碼,我所要的輸出是,但是我得到

​​

我當前的代碼是:

d={} 
while True: 
    try: 
     filename=input("Enter the name of the file to open: ") + ".txt" 
     with open(filename,"r") as f: 
      for line in f: 
       splitLine=line.split() 
       d[splitLine[0]]=splitLine[1:] 
       #print(line, end="") 
       print(d) 
      break 

    except FileNotFoundError: 
     print("File name does not exist; please try again") 

我需要做什麼才能停止打印上面的行。我相信,它與做:

d[splitLine[0]]=splitLine[1:] 

,但我不知道如何解決這個問題

+0

刪除評論 – Monkeybrain

+1

你能不能給你想要的d是什麼樣子的例子嗎? –

+1

爲什麼你使用遊戲板而不是2D列表字典? –

回答

0

正如其他人所指出的,列表可能是您的遊戲板更好的選擇。你可以是這樣做的:

d = [] 
while True: 
    try: 
     filename = 'foo.txt' 
     with open(filename, "r") as f: 
      for line in f: 
       d.append(list(line.strip())) 
      break 

    except FileNotFoundError: 
     print("File name does not exist; please try again") 

print(d) 

for line in d: 
    print(''.join(line)) 

此輸出:

[['A', 'B', 'C'], ['C', 'A', 'B'], ['B', 'C', 'A']] 
ABC 
CAB 
BCA 

for循環打印出來完全按照您在

+0

謝謝;你能解釋一下'd.append(list(line.strip())'''部分嗎?我明白append將列表(行)添加到列表「d」的末尾;但是帶子究竟做了什麼? – Xrin

+1

當您在文件中的每一行讀,還有在該行的最後一個換行符。調用'列表( 'ABC \ N')''給出[ 'A', 'B', 'C', '\ n']'。爲了擺脫換行的,你可以使用['str.strip()'](https://docs.python.org/2/library/string.html#string.strip)刪除多餘的空格。 – JCVanHamme

0

它更有道理你的主板存儲在2維列表:

with open(filename, 'r') as f: 
    board = [list(line) for line in f.read().splitlines()] 

for row in board: 
    print(row) 

輸出:

['A', 'B', 'C'] 
['C', 'A', 'B'] 
['B', 'C', 'A'] 

然後,可以基於其座標選擇一個值:

board[0][0] # top left 'A' 
board[2][2] # bottom right 'A' 
0

讀它你在指出問題的正確。

你需要空出變量:

d 

每次循環。

例子:

d={} 
while True: 
    try: 
     filename=input("Enter the name of the file to open: ") + ".txt" 
     with open(filename,"r") as f: 
      for line in f: 
       splitLine=line.split() 
       d[splitLine[0]]=splitLine[1:] 
       print(line, end="") 
       d={} 
      break 

    except FileNotFoundError: 
     print("File name does not exist; please try again") 
0

首先,你應該更好地只是把它作爲(列表或列表)的列表,而不是使其成爲一個字典。

d=[] 
while True: 
    try: 
     #filename=input("Enter the name of the file to open: ") + ".txt" 
     with open("file.txt","r") as f: 
      for line in f: 
       splitLine=line.split() 
       d.extend(splitLine) 
       #print(line, end="") 

      break 

    except FileNotFoundError: 
     print("File name does not exist; please try again") 

for elem in d: 
     print elem 

如果您使用像這樣的列表結構,然後最後使用循環遍歷所有元素,您將得到所需的輸出。

輸出:

ABC 
CAB 
BCA