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'}
相关推荐
nbsaas-boot1 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
仗剑_走天涯1 小时前
基于pytorch.nn模块实现线性模型
人工智能·pytorch·python·深度学习
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴6 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc7 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
ajassi20007 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛7 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
Deng9452013148 小时前
基于Python的旅游数据可视化应用
python·numpy·pandas·旅游·数据可视化技术
2401_878624798 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习