python - 如何制作 2 克带状疱疹?

标签 python

我有从一些教程中获得的代码-:

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 转换为 set 它会删除重复的单词,而且我还需要它作为我的主要代码的列表,该代码以列表的形式处理一个巨大的文本文件。 为什么我会得到这个“无法散列的列表”?我们不能将列表作为参数传递吗?

最佳答案

问题在于您的 get_shingle() 函数生成列表。 列表不可散列,这是构建集合所必需的。您可以通过生成元组(可散列)而不是列表来轻松解决此问题。

转换代码中的以下行:

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')}

关于python - 如何制作 2 克带状疱疹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081237/

相关文章:

python - 检测常见文件类型

python - 获取 session 的 Quickblox 收到 "Unexpected signature"错误

python - TypeError : sequence item 0: expected string, int 找到

python - python 中的赫斯特指数

Python 类属性不继承

python - 如何使用 lxml 删除标题/尾随处理指令

python - 有没有办法禁用Python调试器的pdb库set_trace默认别名?

python - 调用 super() 时,元类如何与 MRO 列表一起工作?

python - 如何在 Vim 插件输出中为单词着色

python - Pandas 数据框 : get maxima of a column after grouping by another coumn