2016-03-15 84 views
2

我想在一个以特定字符(这里是“c”)开头的文件中打印一组行,但每当我尝试将列表转换为设置将一个列表变成一组 - Python

我有以下代码:

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' 
+0

如果line.startswith((“c”))“是一个生成器表达式,则此”line.rstrip()。split()for line in z。也许是这样。 –

回答

1

即使你删除掉.split(),你将与你的组线结束。

+0

谢谢亲爱的先生,这解决了我的问题! – Karatawi

0

为了有效地查找窗口,set作品只用哈希的类型。特别是可排序的类型必须是不可变的,也就是说,它们在构建之后可能不会改变。既然你可以追加元素并从列表中删除元素,它是可变的。相比之下,一个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()) 
+0

谢谢你,这也帮助了我! – Karatawi

相关问题