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'}
相关推荐
思则变2 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络3 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find4 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取5 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector6 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习7 小时前
Python入门Day2
开发语言·python
Vertira7 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉7 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗7 小时前
黑马python(二十四)
开发语言·python
晓13138 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr