2016-11-28 170 views
1

下面的代码:类型错误:列表索引必须是整数或片,而不是STR字典蟒蛇

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

行:

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 
+0

TNX很多关于帮助 – Tukanoid

相关问题