[ Python ] set集合及函数的使用
1. set类型
set 和 dict 类似,也是一组 key 的集合,但是不存储 value. 由于 key 不重复,所以,在 set 中, 没有重复的 key 集合是可变类型
(1)集合的创建
# 第一种方式创建 set 类型
>>> print(type(set1), set1)
<class 'set'> {1, 3, 6, 'z', 'a', 'b'} # 第二种方式创建 set 类型
>>> set2 = set(['z', 'a', 'b', 3, 6, 1])
>>> print(type(set2), set2)
<class 'set'> {1, 3, 6, 'z', 'a', 'b'} # 第三种方式创建 set 类型
>>> set3 = set('hello')
>>> print(type(set3), set3)
<class 'set'> {'o', 'e', 'l', 'h'}
2. set 工厂函数
(1)add(self, *args, **kwargs)
新增一个元素到集合
set1 = {'a', 'z', 'b', 4, 6, 1}
set1.add(8)
set1.add('hello')
print(set1) # 执行结果:
# {'b', 1, 'a', 4, 6, 8, 'hello', 'z'}
(2) clear()
清空所有集合元素
set1 = {'a', 'z', 'b', 4, 6, 1}
set1.clear()
print(set1) # 执行结果:
# set()
(3)copy()
拷贝整个集合并赋值给变量
set1 = {'a', 'z', 'b', 4, 6, 1}
set2 =set1.copy()
print(set2) # 执行结果:
# {1, 'a', 4, 6, 'b', 'z'}
(4)pop()
随机删除集合中一个元素,可以通过变量来获取删除的元素
set1 = {'a', 'z', 'b', 4, 6, 1}
ys = set1.pop()
print('set1集合:', set1)
print('删除的元素:', ys) # 执行结果:
# set1集合: {4, 6, 'z', 'a', 'b'}
# 删除的元素: 1
(5)remove(self, *args, **kwargs)
删除集合中指定的元素,如果该集合内没有该元素就报错
set1 = {'a', 'z', 'b', 4, 6, 1}
set1.remove('a')
print(set1)
set1.remove('x')
print(set1) # 执行结果:
# {1, 4, 6, 'b', 'z'}
# Traceback (most recent call last):
# File "D:/learn_python/learn_python/day13/s1.py", line 43, in <module>
# set1.remove('x')
# KeyError: 'x'
(6)discard(self, *args, **kwargs)
删除集合中指定的元素,如果该集合内没有该元素也不会报错
set1 = {'a', 'z', 'b', 4, 6, 1}
set1.discard('a')
print(set1)
set1.discard('y')
print(set1) # 执行结果:
# {1, 4, 6, 'b', 'z'}
# {1, 4, 6, 'b', 'z'}
pop() 、remove() 、 discard() 三个集合删除函数比较:
pop() 随机删除集合中一个元素remove() 删除集合中指定的元素,如果集合中没有指定的元素,程序报错!
discard() 删除集合中指定的元素,如果集合中没有指定的元素,程序正常运行。
(7) intersection & :交集; union | :并集合; difference - : 差集
set1 = {'a', 'b', 'x', 'y'}
set2 = {'i', 'j', 'b', 'a'} # 交集
print(set1 & set2)
print(set1.intersection(set2)) # 执行结果:
# {'a', 'b'}
# {'a', 'b'} # 并集
print(set1 | set2)
print(set1.union(set2)) # 执行结果:
# {'y', 'j', 'a', 'b', 'x', 'i'}
# {'y', 'j', 'a', 'b', 'x', 'i'} # 差集
print(set1 - set2)
print(set1.difference(set2))
print(set2 - set1)
print(set2.difference(set1)) # 执行结果:
# {'y', 'x'}
# {'y', 'x'}
# {'j', 'i'}
# {'j', 'i'}
(8)difference_update ()
求差集,并赋值给源集合
set1 = {'a', 'b', 'x', 'y'}
set2 = {'i', 'j', 'b', 'a'}
set1.difference_update(set2)
print(set1) # 执行结果:
# {'y', 'x'}
(9)intersection_update()
求交集,并赋值给源集合
set1 = {'a', 'b', 'x', 'y'}
set2 = {'i', 'j', 'b', 'a'} set1.intersection_update(set2)
print(set1) # 执行结果:
# {'b', 'a'}
(10)symmetric_difference() 和 ^ 符号效果一样
求交叉补集
set1 = {'a', 'b', 'x', 'y'}
set2 = {'i', 'j', 'b', 'a'} print('symmetric_difference:', set1.symmetric_difference(set2))
print('^:', set1 ^ set2) # 执行结果:
# symmetric_difference: {'x', 'i', 'y', 'j'}
# ^: {'x', 'i', 'y', 'j'}
(11)symmetric_difference_update()
求交叉补集并赋值给源集合
set1 = {'a', 'b', 'x', 'y'}
set2 = {'i', 'j', 'b', 'a'} set1.symmetric_difference_update(set2)
print(set1) # 执行结果:
# {'y', 'i', 'j', 'x'}
(12)update()
更新集合,参数为可迭代对象
set1 = {'a', 'b', 'x', 'y'} set1.update(('hello', 'world'))
print(set1) # 执行结果:
# {'hello', 'world', 'b', 'a', 'y', 'x'}
add() 和 update() 比较:
add(): 只能添加一个元素到集合
update(): 可以添加多个元素到集合,参数为 iterable
使用 frozenset 定义不可变集合
s = frozenset('hello')
print(s) # 执行结果:
# frozenset({'h', 'e', 'o', 'l'})
使用 frozenset 定义的集合,没有 add 或者 pop 等方法
3. 函数
(1)函数表现形式
python中函数的定义方法:
def test(x):
"The function definitions"
x += 1
return x
def: 定义函数关键字
test: 函数名(): 内可定义参数"": 文档描述(非必要,强烈建议添加函数信息描述)
x+=1 : 泛指代码块或程序处理逻辑
return: 定义返回值
调用运行:可以带参数也可以不带函数名()
使用函数的好处:
代码重用
保持一致性,易维护
可扩展
函数返回值:
返回值 = 0 : 返回 None
返回值 = 1 : 返回 object
返回值数 > 1: 返回 tuple
(2)函数的参数
建议参考:廖老师python3函数的参数
4. 全局变量和局部变量
如果函数的内容无 global 关键字,优先读取局部变量,能读取全局变量,无法对全局变量重新赋值 NAME='FFF',但是对于可变类型,可以对内部元素进行操作;
如果函数中有 global 关键字,变量本质上就是全局变量,可读取可赋值 NAME='fff'
name = 'hkey' def test1():
name = 'xiaofei'
print(name) def test2():
global name
name = 'xxxx' test1()
test2()
print('name:', name) # 执行结果:
# xiaofei
# name: xxxx
如果函数内无 global 关键字:
(1)有声明局部变量
NAME = ['xiaofei', 'hkey'] def test():
NAME = 'sky'
print('name:', NAME) test() # 执行结果:
# name: sky
(2)无声明局部变量
对于可变类型,可以对内部元素进行操作;
NAME = ['xiaofei', 'hkey'] def test():
NAME.append('sky')
print('name:', NAME) test() # 执行结果:
# name: ['xiaofei', 'hkey', 'sky']
如果函数内有 global 关键字
(1)有声明局部变量
NAME = ['xiaofei', 'hkey'] def test():
# 获取全局变量 NAME
global NAME
# 打印全局变量 NAME
print('global NAME:', NAME)
# 将全局变量 NAME 修改为 'test_func'
NAME = 'test_func'
# 打印修改后的全局变量
print('name:', NAME) test() # 执行结果:
# global NAME: ['xiaofei', 'hkey']
(2)无声明局部变量
NAME = ['xiaofei', 'hkey'] def test():
# 获取全局变量 NAME
global NAME
# 打印全局变量 NAME
print(NAME)
# 修改全局变量为 ['sky']
NAME = ['sky']
# 追加全局变量
NAME.append('blue')
# 打印修改后的全局变量
print(NAME) test() # 执行结果:
##['sky','blue']
在代码中我们规定,全局变量名全部使用大写,而局部变量用小写,这边就避免变量名的混淆;
(3)nonlocal 关键字用来在函数或者其他作用域中使用外层变量
def outer():
num = 10
def inner():
nonlocal num # nonlocal 关键字声明
num = 100 # 修改作用域 num 使用方法和 global 一致
print(num)
inner()
print(num) # 该 num 已经在 inner() 中修改过的 outer() # 执行结果:
# 100
# 100
5. 递归函数
(1)函数即变量
def test():
pass t = test # 把函数当作值 赋值给变量 t
print(t) # 执行结果:
# <function test at 0x00000245A2FBA048>
(2)递归函数
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都写成循环的方式,但循环的逻辑不如递归清晰。
def fact(n):
if n == 1:
return 1
return n * fact(n - 1) print(fact(5)) # 执行过程如下:
#
# ===> fact(5)
# ===> 5 * fact(4)
# ===> 5 * (4 * fact(3))
# ===> 5 * (4 * (3 * fact(2)))
# ===> 5 * (4 * (3 * (2 * fact(1))))
# ===> 5 * (4 * (3 * (2 * 1)))
# ===> 5 * (4 * (3 * 2))
# ===> 5 * (4 * 6)
# ===> 5 * 24
# ===> 120
递归函数就像问路一样,有去有回。A问B,B在问C,C知道答案返回给B,B在返回给A
必须有一个明确的结束条件
每次进入更深一层的递归时,问题规模相比上次递归应有所减少
递归效率不高
(3)尾递归优化
尾递归是指,在函数返回的时候,调用自身本身,并且,return 语句不能包含表达式。
def fact(n):
return fact_iter(n, 1) def fact_iter(num, product):
if num == 1:
return product
# return 语句不能包含表达式。递归本身无论调用多少次,都只占用一个栈帧
return fact_iter(num - 1, num * product) # 运行过程:
# fact(5)
# ===> fact_iter(5, 1)
# ===> fact_iter(4, 5)
# ===> fact_iter(3, 20)
# ===> fact_iter(2, 60)
# ===> fact_iter(1, 120)
# ===>120
[ Python ] set集合及函数的使用的更多相关文章
- Python Set集合,函数,深入拷贝,浅入拷贝,文件处理
1.Set基本数据类型 a.set集合,是一个无序且不重复的元素集合 class set(object): """ set() -> new empty set o ...
- Python学习【day04】- Python基础(集合、函数)
集合 #!/usr/bin/env python # -*- coding:utf8 -*- # set集合 只可放不可变的数据类型,本身是可变数据类型,无序 # s = {1,2,3,[1,2,3] ...
- python之集合,函数,装饰器
本节主要内容如下: 1. set集合 2. 函数 -- 自定义函数 -- 内置函数 3. 装饰器 一. set 集合: 一个无序且不重复的序列. tuple算是list和str的杂合(杂交的都有自己的 ...
- python 集合、函数和文件操作
1.set集合 set集合是一个无序.不可重复.可嵌套的序列,基本功能是进行成员关系测试和删除重复元素,可以使用大括号({})或者 set()函数创建集合,注意:创建一个空集合必须用 set() 而不 ...
- (Python)集合、集合的函数
本节我们将学习python的另一种数据类型:集合(set) 1.集合(set) 集合在Python中是一种没有重复元素,且无序的数据类型,且不能通过索引来引用集合中的元素 >>> b ...
- python_way,day3 集合、函数、三元运算、lambda、python的内置函数、字符转换、文件处理
python_way,day3 一.集合 二.函数 三.三元运算 四.lambda 五.python的内置函数 六.字符转换 七.文件处理 一.集合: 1.集合的特性: 特性:无序,不重复的序列 如果 ...
- Python全栈工程师(集合、函数)
ParisGabriel 感谢 大家的支持 你们的阅读评价就是我最好的动力 我会坚持把排版内容以及偶尔的错误做的越来越好 每天坚持 一天一篇 点个订阅吧 灰常感谢 ...
- 跟着ALEX 学python day3集合 文件操作 函数和函数式编程 内置函数
声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/ 一. 集合 集合是一个无序的,不重复的数据组合,主要作用如下 1.去重 把一个列表变成集合 ,就自动去重 ...
- python基础编程: 编码补充、文件操作、集合、函数参数、函数递归、二分查找、匿名函数与高阶函数
目录: 编码的补充 文件操作 集合 函数的参数 函数的递归 匿名函数与高阶函数 二分查找示例 一.编码的补充: 在python程序中,首行一般为:#-*- coding:utf-8 -*-,就是告诉p ...
随机推荐
- POJ1474:Video Surveillance——题解
http://poj.org/problem?id=1474 题目大意:给按照顺时针序的多边形顶点,问其是否有内核. —————————————————————————————— (和上道题目一模一样 ...
- maven的setting.xml文件中只配置本地仓库路径的方法
maven的setting.xml文件中只配置本地仓库路径的方法 即:settings标签下只有一个 localRepository标签,其他全部注释掉即可 <?xml version=&quo ...
- AIM Tech Round (Div. 2) B
B. Making a String time limit per test 1 second memory limit per test 256 megabytes input standard i ...
- Codeforces Round #532 (Div. 2):F. Ivan and Burgers(贪心+异或基)
F. Ivan and Burgers 题目链接:https://codeforces.com/contest/1100/problem/F 题意: 给出n个数,然后有多个询问,每次回答询问所给出的区 ...
- bzoj 3289 Mato的文件管理 树状数组+莫队
Mato的文件管理 Time Limit: 40 Sec Memory Limit: 128 MBSubmit: 4325 Solved: 1757[Submit][Status][Discuss ...
- Idrac6 to manage dell server
最近idrac6挂了,java已经升级了 1.安装firefox浏览器,只有火狐是支持idrac最好的 2.安装JDK 3.配置configure java, 4.添加security,edit si ...
- HDU 5869 Different GCD Subarray Query 树状数组+离线
Problem Description This is a simple problem. The teacher gives Bob a list of problems about GCD (Gr ...
- [洛谷P1822] 魔法指纹
洛谷题目连接:魔法指纹 题目描述 对于任意一个至少两位的正整数n,按如下方式定义magic(n):将n按十进制顺序写下来,依次对相邻两个数写下差的绝对值.这样,得到了一个新数,去掉前导0,则定义为ma ...
- 删除windows上特定目录下以*.rar后缀名的python脚本
import os,fnmatch,datetime,time def all_files(root,pattern='*',single_level=False,yield_folders=Fals ...
- 知问前端——Ajax提交表单
本文,运用两大表单插件,完成数据表新增的工作. 一.创建数据库 创建一个数据库,名称为:zhiwen,表——user表,字段依次为:id.name.pass.email.sex.birthday.da ...