为什么我得到一个不可损坏类型的错误:下面代码中的'list'。

2024-07-04 07:57:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着做wordcount程序。 但是,我被它卡住了。请检查一下是什么故障,我也标错了线。在

def print_words(filename):
  f=open(filename,'rU')
  text=f.read()
  count={}
  for var in text:
    var=var.lower()
    var=var.split()
    if not var in count: // Error Line
      count[var]=1
    else:
      count[var]=count[var]+1
  return count      

谢谢


Tags: textin程序vardefrucountopen
3条回答

将var转换为list:var=var.split()。所以您可以使用in进行检查。相反,您应该使用for。在

同样,最好使用defaultdict来完成这项工作。在

from collections import defaultdict
...
count=defaultdict(int)
for var in text:
    var=var.lower()
    for intem in var.split():
        count[item]+=1
print count

List是一个不能散列的可变类型。参考hashable,我从中引用了相关部分

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are.

非哈希类型不能用作字典键,但在您的情况下,str.split()生成一个列表,您正试图将其用作键。一个简单的解决方案是将其转换为不可变的序列,比如元组

count[tuple(var)]=1

由于在很多情况下,您已经按原样使用了var,因此建议在将其用作字典的键之前,将其包装为内置的元组以将其转换为元组

^{pr2}$

因为var是一个列表,而您正试图将其用作字典中的键。在

列表是不可更改的,因为它们是可变的。在

var转换为元组(tuple(var))或重新考虑代码。在

相关问题 更多 >

    热门问题