Get common elements of most lists in python

Given 4 lists, I want to get items that are common to 3 or more lists.

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
c = [1, 3, 4, 5, 6]
d = [1, 2, 6, 7]

Therefore, there must be a way out [1, 2, 3, 4].

My current code is as follows.

result1 = set(a) & set(b) & set(c)
result2 = set(b) & set(c) & set(d)
result3 = set(c) & set(d) & set(a)
result4 = set(d) & set(a) & set(b)

final_result = list(result1)+list(result2)+list(result3)+list(result4)
print(set(final_result))

It works great and gives the desired result. However, I am interested to know if there is an easy way to do this in Python, that is: are there any built-in functions for this?

+4
source share
4 answers

Using Counter, you can do it as follows:

The code:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
c = [1, 3, 4, 5, 6]
d = [1, 2, 6, 7]

from collections import Counter

counts = Counter(sum(([list(set(i)) for i in (a, b, c, d)]), []))
print(counts)

more_than_three = [i for i, c in counts.items() if c >= 3]
print(more_than_three)

Results:

Counter({1: 4, 2: 3, 3: 3, 4: 3, 5: 2, 6: 2, 7: 1})

[1, 2, 3, 4]
+4
source

Iterate over all lists to create a dict {value: number_of_lists_the_value_appears_in}:

from collections import defaultdict

counts = defaultdict(int)
for list_ in (a, b, c, d):
    for value in set(list_):  # eliminate duplicate values with `set`
        counts[value] += 1

Then in the second step, delete all the values ​​with count < 3:

result = [value for value, count in counts.items() if count >= 3]

print(result)  # [1, 2, 3, 4]
+1

( n , k ). , :

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
c = [1, 2, 3, 4, 4, 5, 6]
d = [1, 2, 6, 7]


lists = [a, b, c, d]
result = []
desired_quanity = 3

for i in range(len(lists) - desired_quanity + 1):   #see point 1 below
    sublist = lists.pop(0)                          #see point 2
    for item in sublist:
        counter = 1   #1 not 0, by virute of the fact it is in sublist
        for comparisonlist in lists:
            if item in comparisonlist:
                counter += 1
                comparisonlist.remove(item)         #see point 3
        if counter >= desired_quanity:   
            result.append(item)

, , , , . , , ( , OP ), .

1) , k, k-1, k.

2) , , , , , . , .

3) , , , , , , , .

aftersort, , .

0

3

-3

Source: https://habr.com/ru/post/1692508/


All Articles