如何使用.setdefault,默认为我填写函数的列表?例如,
import random
foundwords = []
with open("text", "r") as file:
contents = file.read().replace('\n',' ')
words = contents.split(' ')
def findwords(word):
for i in range(len(words) - 1):
if words[i] == word:
if not words[i + 1] == '':
foundwords.append(words[i + 1])
wordsDict = {}
for i in range(len(words) - 1):
findwords(words[i])
wordsDict.setdefault(words[i], foundwords)
del foundwords[:]
def assemble():
start = words[random.randint(0, len(words))]
print(start.capitalize())
assemble()
当我检查wordsDict时,所有列表都是空的。但是,我知道列表已填充。
答案 0 :(得分:1)
使用foundwords
时,您没有复制.setdefault()
列表,因此所有字典元素都引用相同的列表。然后使用del foundwords[:]
删除该列表的所有元素,因此它们都引用该空列表。
将列表添加到词典时复制列表。
for word in words:
findwords(word)
wordsDict.setdefault(word, foundwords[:])
del foundwords[:]
最好更改findwords()
,以便返回新列表而不是写入全局变量。
def findwords(word):
foundwords = []
for i in range(len(words) - 1):
if words[i] == word:
if not words[i + 1] == '':
foundwords.append(words[i + 1])
return foundwords
for words in words:
wordsDict.setdefault(word, findwords(word))