为什么我的代码在使用 .index() 时没有检测到我在此列表中输入到此列表中的任何变量?


wordList = []
counter = 0
y = 1
total = 0
wordTotal = 0
while y == 1:
word = input("enter wordsn")
continued = input("do you want to continue? y or n ")
if continued == "n":
y = 0
total = total + 1
newWords = []
wordList.append(word)
wordCount = wordList.count(word)
totals = []
if wordCount > 1:
wordTotal = wordTotal - 1
whichWord = newWords.index(word)
totals[whichWord] = totals[whichWord] + 1
if wordCount == 1:
wordTotal = total - wordTotal
newWords.append(word)
print(newWords)
totals.append(1)
print(totals)
if wordTotal == 0:
wordTotal = 1
print("the number of different words is", wordTotal)

该程序获取用户输入的单词,并统计某些单词的重复次数和不正确单词的数量。在代码中的第二个if语句中,当我尝试通过数组newWords[]进行索引,并将重复单词的值从1->2、2->3等,上面写着ValueError:"…"不在列表中。但是,当我在第三个if语句中打印newWords列表时,值就在那里。

很抱歉,如果我犯了一个可怕的错误——我对python还比较陌生,非常感谢所有的帮助:D。

如果

if wordCount > 1:
wordTotal = wordTotal - 1
whichWord = newWords.index(word)
totals[whichWord] = totals[whichWord] + 1

单词等于用户输入的第二个单词,你同意吗?但由于你唯一一次在newWords中添加单词是在以下几行中:

if wordCount == 1:
wordTotal = total - wordTotal
newWords.append(word)
print(newWords)
totals.append(1)

当你到达上面的if wordCount > 1:时,newWords中唯一的单词是用户输入的第一个单词,因此第二个单词不在其中,这就是为什么你的错误

让我们一起跑步:用户输入例如";你好";,所以hello是内部单词,你把它添加到中

wordList.append(word)

并且wordcount=1,所以你进入if循环

if wordCount == 1:
wordTotal = total - wordTotal
newWords.append(word)
print(newWords)
totals.append(1)

now newWords=["你好"]

现在用户输入另一个单词;世界;所以现在

word=";世界;wordCounts=2

但是

newWords = ["Hello"]

因为您从未添加";世界;对它但在中

if wordCount > 1:
wordTotal = wordTotal - 1
whichWord = newWords.index(word)
totals[whichWord] = totals[whichWord] + 1

你正试图访问";世界;内部新词

如果您使用的是Python 3.8+,则可以使用以下代码。

可以基于用户输入来控制循环。如果用户只按RETURN,那么input((返回的值将是一个空字符串,它是"falsy"。否则,将单词添加到词典中,并根据需要增加单词计数。

因此,您只需要:

counter = {}
while (word := input('Enter a word or <return> to end: ')):
counter[word] = counter.get(word, 0) + 1
print(*counter.items())

最新更新