将列表变成集合 - Python

Turning a list into a set - Python

我想在文件中打印一组以特定字符开头的行(这里是 "c"),但每当我尝试将列表转换为集合时出现错误

我有以下代码:

z = open("test.txt", "r")
wordList = [line.rstrip().split() for line in z if line.startswith(("c"))]
wordList = set(wordList)
print(wordList)

这是我得到的错误:

Traceback (most recent call last):
   wordList = set(wordList)
TypeError: unhashable type: 'list'

为了高效查找,set 仅适用于可哈希类型。特别是,可散列类型必须是不可变的,这意味着它们在构造后不能更改。由于您可以将元素添加到列表或从列表中删除元素,因此它是可变的。相比之下,a tuple 在构建后是固定的并且是可哈希的。

因此,如果你真的想要一组单词序列,你必须将每行的单词从列表转换为元组:

with open("test.txt", "r") as z:
    wordList = set(tuple(line.rstrip().split()) for line in z if line.startswith("c"))

编辑: 如果您想要一组以 "c" 开头的行中的所有单词,请使用以下内容:

with open("test.txt", "r") as z:
    wordList = set(w for line in z if line.startswith("c") for w in line.rstrip().split())

如果您删除 .split(),您将得到您的一组线条。