TypeError:list indices必须是整数或切片,而不是str dictionary python

时间:2016-11-28 14:49:14

标签: python string python-3.x dictionary

以下是代码:

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

1 个答案:

答案 0 :(得分:2)

该行:

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