【问题标题】:TypeError: list indices must be integers or slices, not str dictionary pythonTypeError:列表索引必须是整数或切片,而不是str字典python
【发布时间】:2017-04-12 08:10:23
【问题描述】:

代码如下:

with open("input.txt", "r") as f:
text = f.read()

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
res = {}
kol = 0
for buk in alphabet:
    if buk in text:
        kol += 1

if kol > 0:
    for bukwa in text:
        if bukwa in alphabet:
            if bukwa not in res:
                res[bukwa.upper()] = text.count(bukwa)
        elif bukwa not in alphabet:
            if bukwa not in res:
                res[bukwa.upper()] = 0
    res = sorted(res)

    with open("output.txt", "w") as f:
        for key in res:
            f.write(key + " " + str(res[key]))

if kol == 0:
    with open("output.txt", "w") as f:
        f.write(-1)

这是错误:

Traceback (most recent call last):
  File "/home/tukanoid/Desktop/ejudge/analiz/analiz.py", line 23, in     <module>
    f.write(key + " " + str(res[key]))
TypeError: list indices must be integers or slices, not str

【问题讨论】:

    标签: python string python-3.x dictionary


    【解决方案1】:

    行:

    res = sorted(res)
    

    没有返回您认为的内容。在字典上使用sort 将对其键进行排序并将它们作为列表返回。

    当您在上下文管理器中执行res[key] 时,您正在使用字符串索引列表,从而导致错误。

    如果您想在字典中排序,可以通过以下两种方式之一进行:

    重命名您创建的列表:

    sorted_keys = sorted(res)
    

    然后在索引仍然引用 dict 名称 res 的同时遍历那些。

    或者,使用OrderedDict,然后像使用普通字典一样遍历其成员:

    from collections import OrderedDict
    
    # -- skipping rest of code --
    
    # in the context manager
    for key, val in OrderedDict(res):
        # write to file
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2020-11-21
      • 2017-10-08
      • 2020-07-11
      • 2022-10-04
      • 2015-12-09
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多