close

How can I calculate the Jaccard Similarity of two lists containing strings in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I calculate the Jaccard Similarity of two lists containing strings in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How can I calculate the Jaccard Similarity of two lists containing strings in Python?

  1. How can I calculate the Jaccard Similarity of two lists containing strings in Python?

    I ended up writing my own solution after all:
    def jaccard_similarity(list1, list2): intersection = len(list(set(list1).intersection(list2))) union = (len(set(list1)) + len(set(list2))) - intersection return float(intersection) / union

  2. calculate the Jaccard Similarity of two lists containing strings in Python

    I ended up writing my own solution after all:
    def jaccard_similarity(list1, list2): intersection = len(list(set(list1).intersection(list2))) union = (len(set(list1)) + len(set(list2))) - intersection return float(intersection) / union

Method 1

I ended up writing my own solution after all:

def jaccard_similarity(list1, list2):
    intersection = len(list(set(list1).intersection(list2)))
    union = (len(set(list1)) + len(set(list2))) - intersection
    return float(intersection) / union

Method 2

For Python 3:

def jaccard_similarity(list1, list2):
    s1 = set(list1)
    s2 = set(list2)
    return float(len(s1.intersection(s2)) / len(s1.union(s2)))
list1 = ['dog', 'cat', 'cat', 'rat']
list2 = ['dog', 'cat', 'mouse']
jaccard_similarity(list1, list2)
>>> 0.5

For Python2 use return len(s1.intersection(s2)) / float(len(s1.union(s2)))

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read