How to know how many numbers in one list are repeated in others?

Asked

Viewed 872 times

1

I have four lists of their values:

 A = [1,2,3,4,5,6,7,8,9,10]
 B = [1,2,3]
 C = [4,5,6] 
 D = [7,8,9,10]

Would it have any function to compare list A with the other three lists and tell how many numbers on list A are repeated with those on the next three lists? For example: List A contains 3 numbers from list B, list A contains 3 numbers from list C, list A contains 4 numbers from list D.

2 answers

3


The structure set has the function intersection, which returns the intersection between the set and another element, such as a list. We can easily define a function that simply transforms one of the lists into a set and returns the size of the intersection (common elements) between a list and another:

A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
B = [1, 2, 3, 5, 11]

def contagem_interseccao(a, b):
    s = set(a)
    return len(s.intersection(b))

print(contagem_interseccao(A, B))  # 4
  • 1

    @Eduardomarques imagine! We’ve all been beginners. I’m glad I could help!

1

You can convert both lists to one set to then use the intersection operator (&) to calculate the amount of elements in common between them:

A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
B = [1, 2, 3, 5, 11]

n = len( set(A) & set(B) )

print( n )

Exit:

4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.