Hoe twee sets samen te voegen in Python

Jinku Hu 30 januari 2023 20 december 2019
  1. A |= B om twee sets samen te voegen in Python
  2. A.update(B) om twee sets samen te voegen in Python
  3. A.union(B) om twee sets samen te voegen in Python
  4. reduce(operator.or_, [A, B]) om twee sets samen te voegen in Python
Hoe twee sets samen te voegen in Python

In deze tutorial zullen we verschillende methoden introduceren om twee sets in Python samen te voegen.

  1. A |= B
  2. A.update(B)
  3. A.union(B)
  4. reduce(operator.or_, [A, B])

A |= B om twee sets samen te voegen in Python

A |= B voegt alle elementen van set toe B aan set A.

>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A |= B
>>> A
{4, 5, 6, 7, 8, 9}

A.update(B) om twee sets samen te voegen in Python

A.update(B) methode is identiek aan A |= B . Het verandert A op zijn plaats.

>>> A = ["a", "b", "c"]
>>> B = ["b", "c", "d"]
>>> A.update(B)
>>> A
["a", "b", "c", "d"]

A.union(B) om twee sets samen te voegen in Python

A.union(B) geeft de unie van sets A en terug B . Het wijzigt de ingestelde set niet, A maar retourneert een nieuwe set.

>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A.union(B)
{1, 2, 3, 4, 5, 6}
>>> A
{1, 2, 3, 4}

Het is identiek aan A | B.

reduce(operator.or_, [A, B]) om twee sets samen te voegen in Python

operator.or_(A, B) retourneert de bitwiser or van A en B , of unie van sets A en B of A en B zijn sets.

reduce in Python 2.x of functools.reduce in zowel Python 2.x als 3.x is de functie van toepassing op de items van iterable.

Daarom reduce(operator.or_, [A, B]) is de or functie van toepassing op A en B . Het is identiek aan de uitdrukking Python 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}

Aandacht

reduce is de ingebouwde functie in Python 2.x, maar is verouderd in Python 3.

Daarom moeten we functools.reduce de codes compatibel maken in Python 2 en 3.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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