将列表转换为set-Python
我想在文件中打印一组以某个字符开头的行(这里是“c”),但每当我试图将列表转换为一个集合时,就会出现错误 我有以下代码:将列表转换为set-Python,python,list,set,list-comprehension,typeerror,Python,List,Set,List Comprehension,Typeerror,我想在文件中打印一组以某个字符开头的行(这里是“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):
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
仅适用于哈希类型。特别是,散列类型必须是不可变的,这意味着它们在构造之后可能不会更改。由于您可以将元素附加到列表并从列表中删除元素,因此它是可变的。相反,元组
在构造之后是固定的,并且是可散列的
因此,如果确实需要一组单词序列,则必须将列表中每行的单词转换为元组:
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()
,您将得到一组行。谢谢您,亲爱的先生,这解决了我的问题!此“line.rstrip().split()(如果line.startswith((“c”))是一个生成器表达式,则表示z中的line。也许是这样。谢谢你,伙计,这也帮了我的忙!