我无法替换python上的列表,我的代码如下。
def words_open():
global words
wordsfile = open("words.txt","r")
words_list = wordsfile.readlines()
words = []
for i in range(len(words_list)):
words.append(words_list[i].strip())
return words_list
return words
def replace_symbol_for_letter(letter,symbol):
print([s.replace(symbol,letter) for s in words])
return words
def enter_pairing():
correct_symbol = False
while correct_symbol == False:
symbol = input("Please enter a symbol: ")
if symbol not in symbols_list:
correct_symbol = False
elif symbol in symbols_list:
correct_symbol = True
correct_letter = False
while correct_letter == False:
letter = input("Please enter a letter: ")
letter = letter.upper()
if letter not in alphabet:
correct_letter = False
elif letter in alphabet:
correct_letter = True
current_pairings.append(symbol and letter)
replace_symbol_for_letter(letter,symbol)
return letter
return symbol
代码运行正常,没有语法错误,但是我无法替换'单词'名单。 当我运行代码时会发生这种情况:
The words are:
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
Please enter a symbol: #
Please enter a letter: A
['A+/084&"', 'A3*A%A+', '8%203:', ',1$&', '!-*%', '.A7&33&', 'A*A71%', "&-&641'2", 'A))85', '9&330*']
Please enter a symbol: +
Please enter a letter: b
['#B/084&"', '#3*#%#B', '8%203:', ',1$&', '!-*%', '.#7&33&', '#*#71%', "&-&641'2", '#))85', '9&330*']
正如您所看到的那样,符号被替换为字母,其工作正常,但是一旦我输入新的符号/字母配对,它就会删除之前的替换并再次替换它。
谢谢!
答案 0 :(得分:1)
在您的代码中,您无法修改words
replace_symbol_for_letter
列表
print([s.replace(symbol,letter) for s in words])
这不会修改单词列表它只会创建一个新的列表,其配对已更改,但words
不会更改
替换它:
words = [s.replace(symbol,letter) for s in words]
print words
这应该成功。
顺便说一句:全球变种是邪恶的:)
答案 1 :(得分:0)
您忘记关闭文件了解它,您应该考虑使用with
语句打开您的文件,它会在您执行操作后自动关闭它。
def words_open():
with open('words.txt', 'r') as file:
words_list = file.readlines()
words = [line.split() for line in words_list]
return words_list, words