파이썬에서 두 세트를 결합하는 방법
-
파이썬에서 두 세트를 결합하는
A |= B -
파이썬에서 두 세트를 결합하는
A.update(B) -
A.union(B)파이썬에서 두 세트에 합류 -
reduce(operator.or_, [A, B])파이썬에서 두 세트를 결합
이 자습서에서는 두 가지 파이썬 세트에 조인하는 다양한 방법을 소개합니다.
A |= BA.update(B)유니온(B)감소 (operator.or_, [A, B])
파이썬에서 두 세트를 결합하는 A |= B
A |= B 는 B 의 모든 요소를 추가하여 A 를 설정합니다.
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A |= B
>>> A
{4, 5, 6, 7, 8, 9}
파이썬에서 두 세트를 결합하는 A.update(B)
A.update(B)방법은 A |= B 와 동일합니다. A를 제자리에 설정합니다.
>>> A = ["a", "b", "c"]
>>> B = ["b", "c", "d"]
>>> A.update(B)
>>> A
["a", "b", "c", "d"]
A.union(B)파이썬에서 두 세트에 합류
A.union(B)는 A 와 B 집합의 합집합을 반환합니다. 세트 A 를 수정하지 않고 새로운 세트를 반환합니다.
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A.union(B)
{1, 2, 3, 4, 5, 6}
>>> A
{1, 2, 3, 4}
A | B.
reduce(operator.or_, [A, B])파이썬에서 두 세트를 결합
operator.or_(A, B)는 A 와 B 의 비트 단위 or 또는 집합 집합을 반환합니다. A 와 B 가 설정되어 있으면 A 와 B.
Python 2.x 의 reduce 또는 Python 2.x 와 3.x 의 functools.reduce 는 iterable 의 항목에 함수를 적용합니다.
따라서 reduce(operator.or_, [A, B])는 or 함수를 A 와 B 에 적용합니다. 파이썬 표현식 A | B
>>> import operator
>>> from functools import reduce
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> reduce(operator.or_, [A, B])
{4, 5, 6, 7, 8, 9}
reduce 는 Python 2.x 에 내장 된 함수이지만 Python 3에서는 더 이상 사용되지 않습니다.
따라서 파이썬 2와 3에서 코드를 호환 가능하게하려면 functools.reduce 를 사용해야합니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook