我有一些教程中的代码-:
list1 = [['hello','there','you','too'],['hello','there','you','too','there'],['there','you','hello']]
def get_shingle(size,f):
#shingles = set()
for i in range (0,len(f)-2+1):
yield f[i:i+2]
#shingles1 = set(get_shingle(list1[0],2))
#shingles2 = set(get_shingle(list1[1],2))
shingles1 = set(get_shingle(2,list1[0]))
shingles2 = set(get_shingle(2,list1[1]))
print shingles1
print shingles2
print "done"当我试图运行这段代码时,我得到了一个错误-:
Traceback (most recent call last):
File "E:\Research\Shingle Method\create_shingle.py", line 10, in <module>
shingles1 = set(get_shingle(2,list1[0]))
TypeError: unhashable type: 'list'如果设置了list1,那么错误就不会出现。但是我不能将list1转换为,它移除重复的单词,而且我还需要它作为我的主要代码的列表,它以列表的形式处理一个巨大的文本文件。为什么我会收到这份“难以掌握的名单”?我们就不能把名单当作论据吗?
发布于 2016-10-17 08:22:41
问题在于,您的get_shingle()函数生成lists。列表是不可理解的,这是构建一个集合所需要的。您可以通过生成一个元组(这是可以理解的)来轻松地解决这个问题,而不是一个列表。
转换代码中的下列行:
yield tuple(f[i:i+2])这将产生以下结果:
list1 = [['hello','there','you','too'],['hello','there','you','too','there'],['there','you','hello']]
def get_shingle(size,f):
#shingles = set()
print(f)
for i in range (0,len(f)-2+1):
yield tuple(f[i:i+2])
shingles1 = { i for i in get_shingle(2,list1[0])}
print(shingles1)和产出:
['hello', 'there', 'you', 'too']
{('you', 'too'), ('hello', 'there'), ('there', 'you')}发布于 2016-10-17 08:17:42
因为yield命令返回生成器。将生成器转换为集合将触发不可访问的类型错误。
您可以通过简单的更改来使代码工作。
shingles1 = get_shingle(2,list1[0])
lst = [x for x in shingles1]这将给出来自list1[0]的所有重要信息,并将其放入lst中。
发布于 2016-10-17 08:42:43
生成一个生成器,集合(迭代器)需要一个不可变的迭代器。
所以像这样的东西会起作用
shingles1 = set(get_shingle(2,list1[0]))
set(tuple(x) for x in shingles1)https://stackoverflow.com/questions/40081237
复制相似问题