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'}
相关推荐
MinggeQingchun1 小时前
Python - 爬虫-网页解析数据-库lxml(支持XPath)
爬虫·python·xpath·lxml
Python自动化办公社区2 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python
weixin_贾3 小时前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演
张槊哲3 小时前
函数的定义与使用(python)
开发语言·python
船长@Quant4 小时前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
偶尔微微一笑4 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
船长@Quant6 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手6 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin
liuweidong08026 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
CH3_CH2_CHO7 小时前
不吃【Numpy】版
开发语言·python·numpy