Come unire due set in Python
-
A |= Bper unire due set in Python -
A.update(B)per unire due set in Python -
A.union(B)per unire due set in Python -
reduce(operator.or_, [A, B])per unire due insiemi in Python
In questo tutorial, introdurremo diversi metodi per unire due set in Python.
A |= BA.update(B)A.union(B)reduce(operator.or_, [A, B])
A |= B per unire due set in Python
A |= B aggiunge tutti gli elementi del set B al set A.
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A |= B
>>> A
{4, 5, 6, 7, 8, 9}
A.update(B) per unire due set in Python
Il metodo A.update(B) è identico a A |= B. Esso modifica l’impostazione di A in posizione.
>>> A = ["a", "b", "c"]
>>> B = ["b", "c", "d"]
>>> A.update(B)
>>> A
["a", "b", "c", "d"]
A.union(B) per unire due set in Python
A.union(B) restituisce l’unione dei set A e B. Non modifica il set A in posizione, ma restituisce un nuovo 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}
È identico a A | B.
reduce(operator.or_, [A, B]) per unire due insiemi in Python
operator.or_(A, B) restituisce il bitwiser o di A e B, o l’unione di insiemi.
A e B se A e B sono impostate.
reduce in Python 2.x o [functools.reduce in entrambi Python 2.x e 3.x applica la funzione alle voci di iterabili.
Pertanto, reduce(operator.or_, [A, B]) applica la funzione o alle voci A e B. È l’identica all’espressione 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}
reduce è la funzione incorporata in Python 2.x, ma è deprecata in Python 3.
Pertanto, dobbiamo usare functools.reduce per rendere i codici compatibili in Python 2 e 3.
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