Union类型和集合的union()方法-set.union()

Union类型和集合的Union 方法

一、Union类型

1.Union类型由来

Python中的Union类型是 3.10版本引入的新功能之一。它是一种特殊的类型注释,用于表示一个变量可以包含多种数据类型。一般情况下,一个变量只能包含一种数据类型,但是使用Union类型可以创建一个变量,可以包含多种类型的数据。

2.Union类型的语法

python 复制代码
from typing import Union

def func(name: str, age: Union[int, float]) -> None:
   // function content

Union[int, float]表示age参数可以是int型或float型。

3.Union类型的使用

下面是一个示例代码,展示了如何使用Union类型创建包含多种不同数据类型的变量。

python 复制代码
from typing import Union

def get_value(x: Union[int, str]) -> Union[int, str]:
    if isinstance(x, int):
        return x + 1
    elif isinstance(x, str):
        return x + "1"

value1 = get_value(10)
value2 = get_value("hello")

print(value1)
print(value2)

运行结果:

python 复制代码
11
hello1

4.一些等价写法

  1. vars和Union一些等价写法
python 复制代码
vars: Union[int, str]
# 等价于
vars: [int or str]


vars: Union[int]
# 等价于
vars: int

2.Union和基本类型等价写法

python 复制代码
Union[int] == int

3.重复的类型参数会自动忽略掉

python 复制代码
Union[int, str, int] == Union[int, str]

4.自动忽略类型参数顺序

python 复制代码
Union[int, str] == Union[str, int]

5.Union 嵌套 Union 会自动解包

python 复制代码
Union[Union[int, str], float] == Union[int, str, float]

二、Set.union()

python集合union方法返回多个集合的并集,并集中的元素包含所有集合的元素,参与计算的集合都是它的子集。

union() 语法

python 复制代码
s.union(s1, s2 ...)

参数:

  • s1 必传,至少传入一个集合对象进行并集运算
  • s2 如果有多个集合参与计算,则可以传入s2, s3 ...
    返回值:
  • 返回一个新集合,新集合是所有集合的并集

示例代码

python 复制代码
t1 = {'python', 'c', 'java'}
set2 = {'python', 'java'}
set3 = {'node', 'java', 'c'}

# 计算set1 与 set2 的并集
print(set1.union(set2))          # {'java', 'python', 'c'}

## 计算 set1 , set2, set3 三个集合的并集
print(set1.union(set2, set3))    # {'java', 'python', 'node', 'c'}
相关推荐
dreadp41 分钟前
解锁豆瓣高清海报(二) 使用 OpenCV 拼接和压缩
图像处理·python·opencv·计算机视觉·数据分析
Tester_孙大壮1 小时前
第32章 测试驱动开发(TDD)的原理、实践、关联与争议(Python 版)
驱动开发·python·tdd
小王子10244 小时前
设计模式Python版 组合模式
python·设计模式·组合模式
Mason Lin6 小时前
2025年1月22日(网络编程 udp)
网络·python·udp
清弦墨客6 小时前
【蓝桥杯】43697.机器人塔
python·蓝桥杯·程序算法
RZer8 小时前
Hypium+python鸿蒙原生自动化安装配置
python·自动化·harmonyos
CM莫问9 小时前
什么是门控循环单元?
人工智能·pytorch·python·rnn·深度学习·算法·gru
查理零世9 小时前
【算法】回溯算法专题① ——子集型回溯 python
python·算法
圆圆滚滚小企鹅。10 小时前
刷题记录 HOT100回溯算法-6:79. 单词搜索
笔记·python·算法·leetcode
纠结哥_Shrek10 小时前
pytorch实现文本摘要
人工智能·pytorch·python