2013-12-08 47 views
0

我正在嘗試構建一個簡單的遊戲,但我在更新列表時遇到問題並重新打印它的任何想法?更新列表並重新打印它?

我從一個txt文件中提取一些細節並將它們放入一個列表中。我列出了這個清單,這個工作。

我使用.replace進行更新,但是當我重新打印列表時,它只打印列表中的最後一個項目。這已被正確更新。我怎樣才能得到它,所以它再次打印已更新的整個列表?

任何想法???

這裏是我的代碼:

print("Can you solve the puzzle? \nBelow are some words in code form can you crack the code and figue out\nthe words?\n") 
words = open ("words.txt", "r") 
lines_words = words.readlines() 

for line_words in lines_words: 
    print (line_words) 

words.close() 

print("\nHere are some clues to help you!\n") 

clues = open ("clues.txt", "r") 
print (clues.read()) 

clues.close() 

### 

print ("\nThis is what we have so far....") 

# define the function 
def replace_all(text, dic): 
    for i, j in dic.items(): 
     text = text.replace(i, j) 
    return text 


# dictionary with key:values. 
reps = {'#':'A', '*':'M', '%':'N'} 

txt = replace_all(line_words, reps) 
print (txt) 

回答

0

你正在兩個錯誤:

  1. 重用line_words名稱與for循環:

    for line_words in lines_words: 
        print (line_words) 
    

    這取代舊的價值(一個清單)機智h每行的列表中依次。在最後一次迭代之後,意味着line_words已被最後一行代替。

    在使用不同的名稱循環:

    for line in lines_words: 
        print (line) 
    
  2. 你需要使用另一個循環中的行替換文本:

    for line in line_words: 
        txt = replace_all(line, reps) 
        print (txt) 
    

    這會掩蓋你的話只是爲了打印,在迭代中,而不是更改line_words中包含的原始字符串。

+0

謝謝你這幫了很多!我可以繼續構建我的遊戲並使用TKinter開發界面。 – user3078517