【问题标题】:TypeError: list indices must be integers, not str in list problemTypeError:列表索引必须是整数,而不是列表问题中的str
【发布时间】:2020-12-02 06:33:37
【问题描述】:
book_title =  ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
word_counter = []
for words in book_title:
    if words not in word_counter:
        word_counter[words]=1
    else:
        word_counter[words]+=1

我遇到了需要更正的错误类型,我应该做些什么来改进这一点

TypeError: 列表索引必须是整数,而不是 str

【问题讨论】:

  • 你需要创建字典而不是列表来保持字数统计
  • 你可能需要一个字典。word_counter = {}。
  • 或者只是:word_counter = Counter(book_title)
  • 请提供完整的追溯

标签: python python-3.x list


【解决方案1】:

正如其他人所指出的,您在概念上尝试使用字典,而不是列表。但是,对于计数,有一个专门的字典,collections.Counter,您可以按如下方式使用:

from collections import Counter

word_counter = Counter(book_title)

这样做更容易。

【讨论】:

    【解决方案2】:

    您应该使用字典来计算单词。最好使用defaultdict 来执行此操作。

    from collections import defaultdict
    
    book_title =  ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
    word_counter = defaultdict(int)
    for word in book_title:
        word_counter[word] += 1
    

    【讨论】:

    • 如果你使用集合模块,我认为实际上使用 Counter 更好。
    • 是的,我想这在某些情况下也很有用。
    【解决方案3】:
    book_title =  ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
    word_counter = {} #use dict not list
    for words in book_title:
        if words not in word_counter:
            word_counter[words]=1
        else:
            word_counter[words]+=1
    

    为键值对使用字典。 List 只存储值。您试图通过列表中不可能的键访问该值。

    Python 方式

    from collections import Counter
    book_title =  ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
    word_counter = Counter(book_title)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多