【问题标题】:Why do I get a TypeError in this Python program? [duplicate]为什么我在这个 Python 程序中得到一个 TypeError? [复制]
【发布时间】:2019-11-16 11:12:57
【问题描述】:
# I'm trying to make a Zipf's Law observation using a dictionary that stores every word, and a counter for it. I will later sort this from ascending to descending to prove Zipf's Law in a particular text. I'm taking most of this code from Automate the Boring Stuff with Python, where the same action is performed, but using letters instead.
message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    wordsRanking.setdefault(words[i], 0)
    wordsRanking[i] += 1   
print(wordsRanking)    

这段代码给了我以下错误:
TypeError: list indices must be integers or slices, not str
我该如何解决这个问题?我将不胜感激。

【问题讨论】:

  • 因为 i 是一个词,而不是一个索引; Python for 循环遍历元素。
  • 许多已经回答的问题可以帮助你。只需在搜索栏中输入您的错误消息

标签: python python-3.x dictionary zipf


【解决方案1】:

如果我们调试:

message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    print(i) ### add this
    wordsRanking.setdefault(words[i], 0)
    wordsRanking[i] += 1   
print(wordsRanking)   

输出是:

the ## this is what printed. and word[i] is now equal to word["the"]. that raise an error
Traceback (most recent call last):
  File "C:\Users\Dinçel\Desktop\start\try.py", line 6, in <module>
    wordsRanking.setdefault(words[i], 0)
TypeError: list indices must be integers or slices, not str

正如您所见,通过 for 循环迭代 words 为我们提供了 word 的元素。不是整数或元素索引。所以你应该使用wordsRanking.setdefault(i, 0):

message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    wordsRanking.setdefault(i, 0)
    wordsRanking[i] += 1   
print(wordsRanking) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多