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'}
相关推荐
DanCheng-studio24 分钟前
毕设 基于机器视觉的驾驶疲劳检测系统(源码+论文)
python·毕业设计·毕设
carpell26 分钟前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割
一只小波波呀1 小时前
打卡第48天
python
zstar-_1 小时前
一套个人知识储备库构建方案
python
Amo Xiang2 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法
江梦寻2 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing2 小时前
Python——MySQL远程控制
开发语言·python·mysql
miniwa2 小时前
Python编程精进:CSV 模块
python
老胖闲聊9 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1189 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn