Как найти пересечение нескольких множеств питон

If you don’t have Python 2.6 or higher, the alternative is to write an explicit for loop:

def set_list_intersection(set_list):
  if not set_list:
    return set()
  result = set_list[0]
  for s in set_list[1:]:
    result &= s
  return result

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print set_list_intersection(set_list)
# Output: set([1])

You can also use reduce:

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print reduce(lambda s1, s2: s1 & s2, set_list)
# Output: set([1])

However, many Python programmers dislike it, including Guido himself:

About 12 years ago, Python aquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches. But, despite of the PR value, I think these features should be cut from Python 3000.

So now reduce(). This is actually the one I’ve always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what’s actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it’s better to write out the accumulation loop explicitly.

In this article, a List of sets is given our task is to write a program to perform their intersection using Python.

Examples of finding the intersection of multiple sets

Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
Output : {3, 5}
Explanation : 3 and 5 is present in all the sets.

Method 1: Using a Logical operator

This is the simplest method to get the intersection of multiple sets using the Python logical operator

Python3

set_1 = {21, 10, 5, 11, 12}

set_2 = {5, 21, 3, 8, 9}

set_3 = {1, 21, 5, 3, 4, 5}

set4 = set1 & set2 & set3

print(set4)

Output:

{21, 5}

Method 2: Using intersection() + * operator

In this, we will perform tasks to get intersections using intersection() and the * operator is used to pack all the sets together.

Python3

test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]

print("The original list is : " + str(test_list))

res = set.intersection(*test_list)

print("Intersected Sets : " + str(res))

Output:

The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}

Method 3: Using reduce() + and_ operator

In this, we will perform intersection using and_ operator and Python reduce() does the task of getting all the sets packed together for the required operation.

Python3

from operator import and_

from functools import reduce

test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]

print("The original list is : " + str(test_list))

res = set(reduce(and_, test_list))

print("Intersected Sets : " + str(res))

Output:

The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}

Last Updated :
24 Mar, 2023

Like Article

Save Article

Прежде чем перейти к методу  intersection(), мы должны знать, что такое пересечение. Оно относится к общим элементам двух заданных множеств. Это означает, что если есть два набора и у них есть некоторые общие элементы, то они известны как пересечение обоих множеств.

Пересечение элементов и метод intersection() в Python

Set intersection() в Python — это встроенный метод, используемый для поиска пересечения между заданными множествами. Метод set.intersection() находит пересечение двух или более двух наборов. Он возвращает набор, содержащий сходство между двумя или более наборами.

Метод set.intersection() возвращает множество, которое содержит сходство между двумя или более наборами. Это означает, что возвращаемый набор содержит элементы только из обоих или всех наборов, если сравнение производится более чем с двумя наборами.

Итак, метод set.intersection() используется для нахождения пересечения между заданными множествами. Используя его, мы можем увидеть пересечение двух или более двух множеств.

Синтаксис

set1.intersection(set2,set3,set4...)

Здесь set1 — это набор, в котором мы хотим найти пересечения, а set2, set3, set4 и т. д. — другие наборы.

Возвращаемое значение

Метод set.intersection() возвращает пересечение набора 1 со всеми остальными наборами. Если в качестве параметра функции не передается ни один аргумент, она возвращает поверхностную копию набора set1.

Пример

См. следующий пример кода.

# app.py

# Declaring two sets

# Even nums between 2 and 10
set1 = {2, 4, 6, 8, 10}
# Multiple of 3 between 1 to 10
set2 = {3, 6, 9}

# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
# Now we will find intersection of these two sets
print("intersection of set1 and set2 is: ", set1.intersection(set2))

Выход:

Set1 is:  {2, 4, 6, 8, 10}
Set2 is :  {9, 3, 6}
intersection of set1 and set2 is:  {6}

Итак, здесь, в этом примере, мы видим, что мы объявили два набора четных чисел, кратных 3. Теперь мы нашли их пересечение. Как мы видим, пересечение должно быть 6, потому что только 6 является общим в обоих наборах; выход тоже 6.

Пересечение более чем двух множеств

См. следующий код.

# app.py

# Declaring two sets
# Even nums between 2 and 10
set1 = {2, 4, 6, 8, 10}
# Multiple of 3 between 1 to 10
set2 = {3, 6, 9}
# prime numbers between 1 to 10
set3 = {2, 3, 5, 7}
# odd numbers between 1 to 10
set4 = {1, 3, 5, 7, 9}

# Now we will find intersection of some sets

# intersection of set1 and set2
print("intersection of set1 and set2 is: ", set1.intersection(set2))
# intersection of set3 and set4
print("intersection of set3 and set4 is: ", set3.intersection(set4))
# intersection of set2 and set3
print("intersection of set2 and set3 is: ", set2.intersection(set3))
# intersection of set2 and set3,set4
print("intersection of set2 and set3,set4 is: ", set2.intersection(set3, set4))
# intersection of set1 and set2,set3,set4
print("intersection of set1 and set2,set3,set4 is: ",
set1.intersection(set2, set3, set4))

Выход:

intersection of set1 and set2 is:  {6}
intersection of set3 and set4 is:  {3, 5, 7}
intersection of set2 and set3 is:  {3}
intersection of set2 and set3,set4 is:  {3}
intersection of set1 and set2,set3,set4 is:  set()

В этом примере мы видим, что нашли пересечение множества1 и множества2, множества3 и множества4, множества2 и множества3, поэтому в соответствии с этим выводятся все общие элементы. Точно так же пересечение set2 и set3, set4, равно 3, которые печатаются.

Кроме того, когда мы находим пересечение set2, set3 и set4 с set1, результатом будет None, потому что в них нет общего элемента.

Пересечение (A∩B) двух множеств A и B в Python – это набор, содержащий все элементы, общие для обоих множеств.

Мы также можем выполнить пересечение нескольких множеств. На следующем изображении показан пример пересечения двух и трех множеств.

Пересечение множеств

В Python мы можем использовать функцию set class crossction(), чтобы получить пересечение двух множеств.

Давайте посмотрим на пример.

set1 = set('abcde')

set2 = set('ae')

print(set1)
print(set2)

# two sets intersection
print(set1.intersection(set2))

Вывод:

{'a', 'e', 'b', 'd', 'c'}
{'a', 'e'}
{'a', 'e'}

Пересечение двух множеств в Python

Функция crossction() также принимает несколько заданных аргументов. Давайте посмотрим на еще один пример пересечения нескольких множеств.

set1 = set('abcde')
set2 = set('ae')
set3 = {'a'}
print(set1.intersection(set2, set3))

Вывод: {‘a’}

Пересечение множественных множеств в Python

Как установить пересечение без аргументов?

Мы также можем вызывать функцию crossction() без аргументов. В этом случае копия набора будет возвращена.

Посмотрим, относится ли возвращенная копия к тому же набору или к другому.

set1 = set('ab')
set4 = set1.intersection()
print(set4)

# check if shallow copy or deep copy
set1.add('0')
set1.remove('a')
print(set1)
print(set4)

Вывод:

{'b', 'a'}
{'0', 'b'}
{'c', 'b', 'a'}

( 6 оценок, среднее 2.83 из 5 )

Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.

dict_keys(['finances', 'documentBase', 'versionNumber', 'mongo_id', 'suppliers', 'placingWayCode', 'contractUrl', 'foundation', 'products', 'scan', 'fileVersion', 'contractProcedure', 'economic_sectors', 'signDate', 'fz', 'currentContractStage', 'printFormUrl', 'price', 'protocolDate', 'number', 'regNum', 'currentContractStage_raw', 'loadId', 'attachments', 'customer', 'placing', 'regionCode', 'id', 'currency', 'singleCustomerReason', 'execution', 'publishDate', 'schemaVersion'])

Понравилась статья? Поделить с друзьями:
  • Как найти собаку в строку
  • Cannot use accessory как исправить
  • Как составить табель медицинского работника
  • Как найти массовую долю гидроксида кальция
  • Как составить онлайн список продуктов