How do you know how many numbers in a list are repeated in others?

1

I have four lists with 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 you have some function to compare list A with the other three lists and say how many numbers from list A repeat with those from the next 3 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.

    
asked by anonymous 19.06.2018 / 02:16

2 answers

3

The set structure has the function intersection , which returns the intersection between set and another iterable 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 one 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
    
19.06.2018 / 02:32
1

You can convert both lists to set so you can 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 )

Output:

4
    
19.06.2018 / 05:15