从 3 个列表构建一个集合 – Python
python 243
原文标题 :build a set from 3 lists – Python
我有以下块,我需要将“分数”定义为任何给定两个列表中每组单词的交集/联合。我明白 & 和 |只能成套使用。从studytonight我得到下面的代码应该可以工作,但它给了我> TypeError: unhashable type: ‘list’
corpus = [
["i","did","not","like","the","service"],
["the","service","was","ok"],
["i","was","ignored","when","i","asked","for","service"]
]
{corpus[0],corpus[1],corpus[2]}
有人可以纠正我的错误吗?
# This is my goal - but all in 1 set
set1 = {"i","did","not","like","the","service"}
set2 = {"the","service","was","ok"}
set3 = {"i","was","ignored","when","i","asked","for","service"}
set1&set3
# Even like this it gives the same error, wwhy can't I do it?
set = {
["i","did","not","like","the","service"],
["the","service","was","ok"],
["i","was,"ignored","when","i","asked","for","service"]
}
回复
我来回复-
Grismar 评论
您正在寻找:
corpus = [ ["i","did","not","like","the","service"], ["the","service","was","ok"], ["i","was","ignored","when","i","asked","for","service"] ] intersection = set.intersection(*map(set, corpus))
或者,从更字面的意义上说:
intersection = set(corpus[0]) & set(corpus[1]) & set(corpus[2])
2年前 -
Rajat Jog 评论
你应该使用:
data = list(sum(corpus, [])) # this will convert 2d into single D list result = set(data)
要么
results = set(list(sum(corpus, [])))
2年前