2016-11-28 169 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

相關問題