本篇要点:
数据类型:set集合
函数
文件操作
三元运算(三目运算)和lambda表达式
一、set集合
python中数据类型的一种,是无序并且不重复的数据集合。set源码:
class set(object): """ 创建set集合 set() -> new empty set object 把可迭代的数据类型转换成元组 set(iterable) -> new set object Build an unordered collection of unique elements. """
>>> s1 = {11, 22, 33} >>> print(s1,type(s1)) {33, 11, 22} <class ‘set‘> >>> l1 = [2, 3, 4,] >>> s1 = set(l1) >>> print(l1,type(l1)) [2, 3, 4] <class ‘list‘> >>> print(s1,type(s1)) {2, 3, 4} <class ‘set‘>
# 向集合中增加元素,如果存在,不做任何操作。 def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass
>>> s1 = {11, 22, 33} >>> s1.add(44) >>> print(s1) {33, 11, 44, 22}
# 清空集合中所有的元素 def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass
>>> s1 = {11, 22, 33} >>> print(s1) {33, 11, 22} >>> s1.clear() >>> print(s1) set()
# 浅复制一个集合 只拷贝第一层 def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass # s1.difference(s2) 找到在s1中有,s2中没有的元素,并保存到一个新的集合 def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass
>>> s1 = {11,22,33,} >>> s2 = {22,33,44,} >>> s3 = s1.difference(s2) >>> print("%s \n%s \n%s" % (s1,s2,s3)) {33, 11, 22} {33, 44, 22} {11}
# s1.difference(s2) 找到在s1中有,s2中没有的元素,把结果更新到s1中 def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass
>>> s1 = {11,22,33,} >>> s2 = {22,33,44,} >>> s1.difference_update(s2) >>> print("%s \n%s" % (s1,s2)) {11} {33, 44, 22}
# s1.intersection(s2) 找到即在集合s1中,又在集合s2中的元素,并把结果保存到一个新的集合里。 def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass
>>> s1 = {11,22,33,} >>> s2 = {22,33,44,} >>> s3 = s1.intersection(s2) >>> print("%s \n%s \n%s" % (s1,s2,s3)) {33, 11, 22} {33, 44, 22} {33, 22}
# s1.intersection(s2) 找到即在集合s1中,又在集合s2中的元素,并把结果更新到s1中 def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass
>>> s1 = {11,22,33,} >>> s2 = {22,33,44,} >>> s1.intersection_update(s2) >>> print("%s \n%s" % (s1,s2)) {33, 22} {33, 44, 22}
# 判断两个集合是否有交接,没有交集时返回True,有交集时返回False
def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass
>>> s1 = {11,22,33,} >>> s2 = {22,33,44,} >>> s3 = {1,2,3,} >>> s1.isdisjoint(s2) False >>> s1.isdisjoint(s3) True
# s1.issubset(s2) 判断s1是不是s2的子集
def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass
>>> s1 = {11,22,} >>> s2 = {11,22,33,44,} >>> s3 = {22,33,} >>> s1.issubset(s2) True >>> s1.issubset(s3) False
# s1.issuperset(s2) 判断s1是不是s2的父集 def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass
>>> s1 = {11,22,33,44,55} >>> s1 = {11,22,33,44,55,} >>> s2 = {22,33,55,} >>> s3 = {44,33,66,} >>> s1.issuperset(s2) True >>> s1.issuperset(s3) False
# 任意删除并返回一个元素 def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass
>>> s1 = {11,22,33,44,55,} >>> s1.pop() 33
# 删除指定的一个元素,这个元素必须在集合中,否则报错。区别于discard() def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass
>>> s1 = {11,22,33,} >>> s1.remove(11) >>> print(s1) {33, 22} >>> s1.remove(44) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 44
# 删除指定的一个元素,如果元素不存在不报错。可以起到判断元素是否在集合中时,代码不报错的作用。 def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass
>>> s1 = {11,22,33,} >>> s1.discard(11) >>> print(s1) {33, 22} >>> s1.discard(44) # 44 不在s1中,操作时不报错 >>> print(s1) {33, 22}
# 相当于取两个集合的并集,再把他俩的交集删掉。返回这个新集合。 def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass
>>> s1 = {11,22,33,44,} >>> s2 = {22,44,55,66} >>> s3 = s1.symmetric_difference(s2) >>> print("%s \n%s \n%s" % (s1,s2,s3)) {33, 11, 44, 22} {66, 44, 22, 55} {33, 66, 11, 55}
# s1.symmetric_difference_update(s2) 相当于取s1,s2两个集合的并集,再把他俩的交集删掉。结果赋值给s1 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass
>>> s1 = {11,22,33,44,} >>> s2 = {22,44,55,66} >>> s1.symmetric_difference_update(s2) >>> print("%s \n%s" % (s1,s2)) {33, 66, 11, 55} {66, 44, 22, 55}
# 取两个集合的并集,结果返回到一个新集合中。 def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass
>>> s1 = {11,22,33,44,} >>> s2 = {22,44,55,66} >>> s3 = s1.union(s2) >>> print("%s \n%s \n%s" % (s1,s2,s3)) {33, 11, 44, 22} {66, 44, 22, 55} {33, 66, 11, 44, 22, 55}
# s1.update(s2) 去两个集合的并集,将结果赋值给s1 def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass
>>> s1 = {11,22,33,44,} >>> s2 = {22,44,55,66} >>> s1.update(s2) >>> print("%s \n%s" % (s1,s2)) {33, 66, 11, 44, 22, 55} {66, 44, 22, 55}
二、函数
为什么要创建函数?
提升代码的复用性和可读性
# 使用函数前,是面向过程变成,更具逻辑从上到下一行一行执行。 while True: if cpu利用率 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 硬盘使用空间 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 内存占用 > 80%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接
sendmail函数(使用参数前)
# 使用函数后,就变成函数式,面向对象编程 def 发送邮件(内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件(‘CPU报警‘) if 硬盘使用空间 > 90%: 发送邮件(‘硬盘报警‘) if 内存占用 > 80%: 发送邮件(‘内存报警‘)
sendmail函数(使用参数后)
函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
面向对象:对函数进行分类和封装
1、函数的定义
def
函数名(参数):
函数体
return
a、def——python中表示函数的关键字
b、函数名——定义函数名称,以后根据函数名称来调用函数
c、(参数)——为函数提供数据
d、函数体——定义在函数中的一系列逻辑计算,函数具体功能的代码实现,写在这个里面
e、返回值(return)——当函数执行完毕后,给调用者返回数据
示例1:邮件发送函数
def sendmail(): import smtplib from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(‘邮件内容‘, ‘plain‘, ‘utf-8‘) msg[‘From‘] = formataddr(["武沛齐", ‘[email protected]‘]) msg[‘To‘] = formataddr(["走人", ‘[email protected]‘]) msg[‘Subject‘] = "主题" server = smtplib.SMTP("smtp.126.com", 25) server.login("[email protected]", "WW.3945.5") server.sendmail(‘[email protected]‘, [‘[email protected]‘, ], msg.as_string()) server.quit() sendmail()
sendmail()——无参数
2、参数的使用
示例1中,实现了给[email protected]发用邮件的功能。但是如果我想要给不同的收件人发邮件,就要写好多个函数,起不到复用代码的效果。因此加上参数。
def sendmail(user_email): # user_email 叫做函数sendmail的形式参数,简称形参 import smtplib from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(‘邮件内容‘, ‘plain‘, ‘utf-8‘) msg[‘From‘] = formataddr(["武沛齐", ‘[email protected]‘]) msg[‘To‘] = formataddr(["走人", ‘[email protected]‘]) msg[‘Subject‘] = "主题" server = smtplib.SMTP("smtp.126.com", 25) server.login("[email protected]", "WW.3945.5") server.sendmail(‘[email protected]‘, [user_email, ], msg.as_string()) server.quit() sendmail("[email protected]”) # [email protected]叫做sendmail的实际参数,调用sendmail函数时把这个参数传递给函数来执行。叫做实际参数,简称实参 sendmail(“[email protected]") sendmail(“[email protected]")
sendmail(user_email)——有参数
引入参数后,就可以给上面三个邮箱发送邮件,而不用定义多个函数。
3、多个参数的使用和返回值
示例2:登陆、注册函数
def login(username, password): """ 用于用户登陆 :param username: 用户输入的用户名 :param password: 用户输入的密码 :return: True,登陆成功;False,登录失败 """ with open("db", "r") as f: for i in f: user_pwd_list = i.strip().split(",") if username == user_pwd_list[0] and password == user_pwd_list[1]: return True return False def register(username, password): """ 用于用户注册 :param username: 用户输入的用户名 :param password: 用户输入的密码 :return: None """ item = "\n{username},{password}".format(username=username, password=password) with open("db", "a") as f: f.write(item) print("注册成功") def main(): """ 用于程序执行的入口 :return: 默认返回None """ choice = input("[1:登陆],[2:注册],请输入数字编号:") user = input("请输入用户名:") pwd = input("请输入密码:") if choice == "1": t = login(user, pwd) # 函数的return返回值赋值给t if t is True: print("登陆成功") else: print("登陆失败") elif choice == "2": register(user, pwd) main()
登陆注册
示例中定义了三个函数,login、register、main。前两个函数需要传递用户名和密码两个参数才能正常完成用户的登陆和验证。因此设定两个形参,让调用者传递两个实参来实现功能。而main函数中,函数的返回值赋值给了t,通过对t的值进行判断,实现了打印不同内容的功能。
4、函数参数的更多类型
上面两个示例都是对普通参数的使用,参数还有更多类型,下面一一说明。
# 普通参数 def send(email, user, msg): print(‘发送成功‘, email, user, msg) return True res = send("[email protected]", "Pesen", "发送成功”) # 传递实参时,要按照形参指定的顺序来填写,否则使用了错误的参数,程序很有可能会出现错误。 if res is True: print("发送成功") else: print("发送失败") # 默认参数(默认参数必须放到最后定义,否则会报错) def send(email, user=“Pesen", msg="发送成功”): # 给user、msg两个形参指定默认值 print(‘发送成功‘, email, user, msg) return True res = send("[email protected]”) # 不给send函数传递user,msg的实参,会使用默认值 if res is True: print("发送成功") else: print("发送失败") # 指定参数:可以打破实参传递的顺序 def send2(email, user, msg): print("邮件信息:", email, user, msg) send2(user="Pesen", msg="OK", email="[email protected]") # 动态参数