Home > OS >  build a set from 3 lists - Python
build a set from 3 lists - Python

Time:03-14

I've got below chunk and I need to define 'Score' as the intersection / union for each set of words in any given two lists. I understand & and | could only be used in sets. From studytonight I get that below code shoud work but it's gving me > 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]}

Could someone please correct my mistake?

# 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"]


}

CodePudding user response:

You were looking for:

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

Or, in a more literal sense:

intersection = set(corpus[0]) & set(corpus[1]) & set(corpus[2])

CodePudding user response:

You should use:

data = list(sum(corpus, [])) # this will convert 2d into single D list
result = set(data)

or

results = set(list(sum(corpus, [])))
  • Related