Detailed explanation of Python set union() function, Python merge set

"Author's Homepage": Shibie Sanri wyx
"Author's Profile": CSDN top100, Alibaba Cloud Blog Expert, Huawei Cloud Share Expert, Network Security High-quality Creator
"Recommended Column": Xiaobai Zero Basic "Python Beginner to Master"

union() can "merge" collections

grammar

set.union( set )

parameter

  • set : (required) the set to be merged

return value

  • Return a new merged collection

Example: Merge two collections

set1 = {
    
    1, 2, 3}
set2 = {
    
    4, 5, 6}

new_set = set1.union(set2)

print(new_set)

output:

{
    
    1, 2, 3, 4, 5, 6}

From the pseudo-source code (Python built-in functions cannot see the source code, only the function description is provided), we can see that union() can return the union of multiple sets as a new set.

insert image description here


1. Merge multiple collections

union() can receive multiple parameters, which means that we can merge "multiple collections" at the same time .

set1 = {
    
    1, 2, 3}
set2 = {
    
    4, 5, 6}
set3 = {
    
    7, 8, 9}

new_set = set1.union(set2, set3)

print(new_set)

output:

{
    
    1, 2, 3, 4, 5, 6, 7, 8, 9}

2. Combine other types

The parameter received by union() is an iterable type ( iterable ), which means that we can combine collections with other iterable types.


2.1. Merge strings

"String" is an iterable type that can be merged with a collection.

set1 = {
    
    1, 2, 3}

new_set = set1.union('abc')

print(new_set)

output:

{
    
    1, 2, 3, 'a', 'c', 'b'}

2.2. Merge list

"Lists" are also iterable types that can be merged with collections.

set1 = {
    
    1, 2, 3}
list1 = [4, 5, 6]

new_set = set1.union(list1)

print(new_set)

output:

{
    
    1, 2, 3, 4, 5, 6}

2.3. Merge tuples

"Tuples" are also iterable types that can be merged with collections.

set1 = {
    
    1, 2, 3}
tuple1 = (4, 5, 6)

new_set = set1.union(tuple1)

print(new_set)

output:

{
    
    1, 2, 3, 4, 5, 6}

2.4. Merge dictionaries

"Dictionary" is also an iterable type that can be merged with collections; unlike other types, dictionaries only merge keys, not values.

set1 = {
    
    1, 2, 3}
dict1 = {
    
    'key1': 1, 'key2': 2}

new_set = set1.union(dict1)

print(new_set)

output:

{
    
    1, 2, 3, 'key1', 'key2'}

2.5, merge bytes type

"bytes" is also an iterable type, which can be merged with a collection; but bytes is a byte stream, and characters will be converted and then merged.

set1 = {
    
    1, 2, 3}
bytes1 = b'abc'

new_set = set1.union(bytes1)

print(new_set)

output:

{
    
    1, 2, 3, 97, 98, 99}

2.6. Values ​​cannot be merged

"Value" is not iterable and cannot be merged with a collection, otherwise an error will be reported TypeError: 'int' object is not iterable

set1 = {
    
    1, 2, 3}

new_set = set1.union(11)

output:

insert image description here

Guess you like

Origin blog.csdn.net/wangyuxiang946/article/details/131865901