Python学习笔记_基础篇(六)_Set集合,函数,深入拷贝,浅入拷贝,文件处理

1、Set基本数据类型

a、set集合,是一个无序且不重复的元素集合

class set(object):"""set() -> new empty set objectset(iterable) -> new set objectBuild an unordered collection of unique elements."""def add(self, *args, **kwargs): # real signature unknown"""Add an element to a set,添加元素This has no effect if the element is already present."""passdef clear(self, *args, **kwargs): # real signature unknown""" Remove all elements from this set. 清楚内容"""passdef copy(self, *args, **kwargs): # real signature unknown""" Return a shallow copy of a set. 浅拷贝  """passdef difference(self, *args, **kwargs): # real signature unknown"""Return the difference of two or more sets as a new set. A中存在,B中不存在(i.e. all elements that are in this set but not the others.)"""passdef difference_update(self, *args, **kwargs): # real signature unknown""" Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""passdef 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. 移除指定元素,不存在不保错"""passdef 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.)"""passdef intersection_update(self, *args, **kwargs): # real signature unknown""" Update a set with the intersection of itself and another.  取交集并更更新到A中 """passdef isdisjoint(self, *args, **kwargs): # real signature unknown""" Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""passdef issubset(self, *args, **kwargs): # real signature unknown""" Report whether another set contains this set.  是否是子序列"""passdef issuperset(self, *args, **kwargs): # real signature unknown""" Report whether this set contains another set. 是否是父序列"""passdef pop(self, *args, **kwargs): # real signature unknown"""Remove and return an arbitrary set element.Raises KeyError if the set is empty. 移除元素"""passdef 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. 移除指定元素,不存在保错"""passdef 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.)"""passdef symmetric_difference_update(self, *args, **kwargs): # real signature unknown""" Update a set with the symmetric difference of itself and another. 对称交集,并更新到a中 """passdef 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.)"""passdef update(self, *args, **kwargs): # real signature unknown""" Update a set with the union of itself and others. 更新 """pass

set

b、数据类型模块举例

se = {11,22,33,44,55}
be = {44,55,66,77,88}# se.add(66)
# print(se)    #添加元素,不能直接打印!
#
#
#
# se.clear()
# print(se)          #清除se集合里面所有的值,不能清除单个
#
#
#
# ce=be.difference(se)   #se中存在,be中不存在的值,必须赋值给一个新的变量
# print(ce)
#
#
# se.difference_update(be)
# print(se)                  #在se中删除和be相同的值,不能赋值给一个新的变量,先输入转换,然后打印,也不能直接打印!# se.discard(11)
# print(se)                   #移除指定元素,移除不存在的时候,不会报错# se.remove(11)
# print(se)              #移除指定的元素,移除不存在的会报错# se.pop()
# print(se)               #移除随机的元素
#
#
# ret=se.pop()
# print(ret)              #移除元素,并且可以把移除的元素赋值给另一个变量# ce = se.intersection(be)
# print(ce)        #取出两个集合的交集(相同的元素)# se.intersection_update(be)
# print(se)        #取出两个集合的交集,并更新到se集合中# ret = se.isdisjoint(be)
# print(ret)         #判断两个集合之间又没有交集,如果有交集返回False,没有返回True# ret=se.issubset(be)
# print(ret)         #判断se是否是be集合的子序列,如果是返回True,不是返回Flase# ret = se.issuperset(be)
# print(ret)          #判断se是不是be集合的父序列,如果是返回True,不是返回Flase# ret=se.symmetric_difference(be)
# print(ret)          #对称交集,取出除了不相同的元素# se.symmetric_difference_update(be)
# print(se)          #对称交集,取出不相同的元素并更新到se集合中# ret = se.union(be)
# print(ret)         #并集,把两个元素集合并在一个新的变量中

2、深浅拷贝

a、数字和字符串

对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

import copy
# ######### 数字、字符串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 赋值 ##
n2 = n1
print(id(n2))
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))

b、其他基本数据类型

对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

1、赋值

赋值 ,只是创建一个变量,该变量指向原来内存地址,如:

n1 = {"k1": "zhangyanlin", "k2": 123, "k3": ["Aylin", 456]}n2 = n1

2、浅拷贝

浅拷贝 ,在内存中只额外创建第一层数据

import copyn1 = {"k1": "zhangyanlin", "k2": 123, "k3": ["aylin", 456]}n3 = copy.copy(n1)

3、深拷贝

深拷贝 ,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

3、函数

  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强…
  • 函数传参数传的是引用

.函数的定义主要有如下要点:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等…
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

以上要点中,比较重要有参数和返回值:

def 发送短信():发送短信的代码...if 发送成功:return Trueelse:return Falsewhile True:# 每次执行发送短信函数,都会将返回值自动赋值给result# 之后,可以根据result来写日志,或重发等操作result = 发送短信()if result == False:短信发送失败...

函数的有三中不同的参数:

邮件实例:

def email(p,j,k):import smtplibfrom email.mime.text import MIMETextfrom email.utils import formataddrset = Truetry:msg = MIMEText('j', 'plain', 'utf-8')  #j 邮件内容msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])msg['To'] = formataddr(["走人",'424662508@qq.com'])msg['Subject'] = "k"  #k主题server = smtplib.SMTP("smtp.126.com", 25)server.login("wptawy@126.com", "WW.3945.59")server.sendmail('wptawy@126.com', [p], msg.as_string())server.quit()except:set = Falsereturn Trueformmail = input("请你输入收件人邮箱:")
zhuti    = input("请您输入邮件主题:")
neirong  = input("请您输入邮件内容:")
aa=email(formmail,neirong,zhuti)
if aa:print("邮件发送成功!")
else:print("邮件发送失败!")

2、 内置函数

# abs绝对值
# i = abs(-123)
# print(i)  #返回123,绝对值# #all,循环参数,如果每个元素为真,那么all返回的为真,有一个为假返回的就是假的
# a = all((None,123,456,False))
# print(a)   #返回的为假的,证明中间有False值
#
# #所有的假值有
#     #0,None,空值
## #any  只要之前有一个是真的,返回的就是真
# b = any([11,False])
# print(b)#ascii,去指定对象的类中找__repr__,获取返回值
# #ascii函数
# class Foo:
#     def __repr__(self):
#         return "zhangyanlin"
# obj =Foo()
# r = ascii(obj)
# print(r)# 布尔值返回真或假
# print(bool(1))
# print(bool(0))# #bin二进制
# r = bin(123)
# print(r)# #oct八进制
# r = oct(123)
# print(r)# #int十进制
# r = int(123)
# print(r)# #hex十六进制
# r = hex(123)
# print(r)# #二进制转十进制
# i= int("0b11",base=2)
# print(i)# #八进制转十进制
# i= int("11",base=8)
# print(i)# #十六进制转十进制
# i = int("0xe",base=16)
# print(i)# #数字代表字母
# c = chr(66)
# print(c)# #字母代表数字
# c = ord("a")
# print(c)#bytes,  字节
#字节和字符串的转换
# a = bytes("zhangyanlin",encoding="utf-8")
# print(a)
#bytearray  字节列表#chr(),把数字转换成字母,只适用于ascii码
# a = chr(65)
# print(a)#ord(),把字母转换成数字,只适用于ascii码
# a = ord("a")
# print(a)#callable表示一个对象是否可执行
# def f1():        #看这个函数能不能执行,能发挥True
#     return 123
# f1()
# r = callable(f1)
# print(r)#dir,查看一个类里面存在的功能
# li = []
# print(dir(li))
# help(list)#divmod(),#分页的时候使用
# a = 10/3
# r = divmod(10,3)
# print(r)#compile编译, 把字符串转移成python可执行的代码,知道就行#eval(),简单的表达式,可以给算出来
# b = eval("a + 69" , {"a":99})  #a可以通过字典声明变量去写入
# print(b)#exec,不会返回值,直接输出结果
# exec("for i in range(10):print(i)")# filter对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)
# def f1(x):
#     if x >22:
#         return  True
#     else:
#         return False
#
# ret = filter(f1,[11,22,33,44,55])
# for i in ret:
#     print(i)# ret = filter(lambda x: x > 22, [11, 22, 33, 44, 55, 66, 77])
# for i in ret:
#     print(i)#map(函数,可以迭代的对象,让元素统一操作)
# def f1(x):
#     return x+123
#
# # li = [11,22,33,44,55,66]
# # ret = map(f1,li)
# print(ret)
# for i in ret:
#     print(i)
#
# ret = map(lambda x: x + 100 if x%2==1 else x, [11, 22, 33, 44])
# print(ret)
# for i in ret:
#     print(i)#globals()获取当前所有的全局变量#locals()获取当前所有的局部变量
# ret = "kaszhfiusdhf"
# def fu1():
#     name = 123
#     print(locals())
#     print(globals())
#
# fu1()#hash 对key的优化,相当于给输出一种哈希值
# li = "sdglgmdgongoaerngonaeorgnienrg"
# print(hash(li))#isinstance()判断是不是一个类型
# li = [11,22]
# ret = isinstance(li,list)
# print(ret)#iter创建一个可以被迭代的元素
# obj = iter([11,22,33,44])
# print(obj)
# #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
# ret = next(obj)#max()取最大的值
# li = [11,22,33,44]
# ret = max(li)
# print(ret)#min()取最小值
# li = [11,22,33,44]
# ret = min(li)
# print(ret)#求一个数字的多少次方
# ret = pow(2,10)
# print(ret)#reversed反转
# a = [11,22,33,44]
# b = reversed(a)
# for i in b:
#     print(i)#round 四舍五入
# ret = round(4.8)
# print(ret)#sum求和
# ret = sum((11,22,33,44))
# print(ret)#zip,1 1对应
# li1 = [11,22,33,44,55]
# li2 = [99,88,77,66,89]
# dic = dict(zip(li1,li2))
# print(dic)#sorted 排序
# li = ["1","2sdg;l","57","a","b","A","中国人"]
# lis = sorted(li)
# print(lis)
# for i in lis:
#     print(bytes(i,encoding="utf-8"))# #随机生成6位验证码
# import random
# temp = ''
# for i in range(6):
#     num = random.randrange(0,4)
#     if num ==3 or num ==1:
#         rad1 = random.randrange(0,10)
#         temp+=str(rad1)
#     else:
#         rad2 = random.randrange(65,91)
#         c1 = chr(rad2)
#         temp+=c1
# print(temp)

4、文件处理

a、打开文件

name = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】

“+” 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

"b"表示以字节的方式操作

  • rb 或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

例:

#普通方式打开
# ====pythobnn内部将二进制转换成字符串,通过字符串操作#二进制打开方式
#用户自己操作把字符串转成二进制,然后让电脑识别# 1. 只读模式,r
# a = open("1.log","r")   #打开1.log,赋予只读的权限
# ret = a.read()        #读取文件
# a.close()            #退出文件
# print(ret)             #打印文件内容#2.只写模式,w, 如果不存在会创建文件,存在则清空内容
# a = open("3.log","w")
# a.write("sdfhsuigfhuisg")
# a.close()#3.只写模式,x, 如果不存在会创建文件,存在则报错
# a = open("4.log","x")
# a.write("12345678")
# a.close()#4.追加模式,a,不可读,不存在则创建文件,存在则会追加内容
# a = open("4.log","a")
# a.write("asjfioshf")
# a.close()# "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)#5.只读模式,rb,以字节方式打开,默认打开是字节的方式
# a = open("2.log","rb")    #二进制方式读取2.log文件
# date = a.read()            #定义变量,读文件
# a.close()                  #关闭文件
# print(date)                #打印文件
# str_data = str(date, encoding="utf-8")    #字节转换成utf-8
# print(str_data)            # 打印文件#6.只写模式,wb,
# a = open("2.log","wb")     #打开文件2.log,可写的模式
# date = "中国人"             #定义字符串
# a.write(bytes(date , encoding="utf-8")) #转换成字节,方便计算机识别
# a.close()                    #关闭文件
# print(date)                  #打印出来#7.只写模式,xb,
# a = open("6.log","xb")
# date = "张岩林非常帅"
# # a.write("sakfdhisf")   #字符串形式会报错,计算机不识别,得转换成字节
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)#8.追加模式,ab,
# a = open("5.log","ab")
# date = "!张岩林是个帅小伙子"
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)# #"+"表示具有读写的功能# #9.r+,读写(可读,可写)
# a = open("5.log","r+",encoding="utf-8")
# print(a.tell())    #打开文件后观看指针位置在第几位,默认在起始位置
#
# date = a.read()       #第一次读取,指针读取到最后了,(可以加读取的索引位置,3表示只看前三位)
# print(date)
#
# a.write("太帅了")      #写的时候会把指针调到最后去写
#
# a.seek(0)           #把指针放在第一位进行第二次读取
#
# date = a.read()       #第二次读取
# print(date)
# a.close()#10.w+,写读,(可写,可读),先清空内容,在写之后需要把指针放在第一位才能读
# a = open("5.log","w+",encoding="utf-8")
# a.write("张岩林")        #清空内容写入“张岩林”
# a.seek(0)                 #把指针放在第一位
# date = a.read()           #进行读取
# a.close()                 #退出文件
# print(date)#11.x+,写读,(可写,可读),需要创建一个新文件,文件存在会报错,在写之后需要把指针放在第一位才能读
# a = open("7.log","x+",encoding="utf-8")
# a.write("张岩林")        #清空内容写入“张岩林”
# a.seek(0)                 #把指针放在第一位
# date = a.read()           #进行读取
# a.close()                 #退出文件
# print(date)#12.a+,写读,(可写,可读),打开文件的同时,指针已经在最后了
# a = open("5.log","a+",encoding="utf-8")
# date = a.read()          #第一次读,没数据,因为指针在最后
# print(date)
#
# a.write("张张")          #往最后写入 张
#
# a.seek(0)                #把指针放在第一位,让他进行曲读
# date = a.read()
# print(date)
#
# a.close()

b、操作操作

 class TextIOWrapper(_TextIOBase):"""Character and line based layer over a BufferedIOBase object, buffer.encoding gives the name of the encoding that the stream will bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults to "strict".newline controls how line endings are handled. It can be None, '','\n', '\r', and '\r\n'.  It works as follows:* On input, if newline is None, universal newlines mode isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): # real signature unknown关闭文件passdef fileno(self, *args, **kwargs): # real signature unknown文件描述符  passdef flush(self, *args, **kwargs): # real signature unknown刷新文件内部缓冲区passdef isatty(self, *args, **kwargs): # real signature unknown判断文件是否是同意tty设备passdef read(self, *args, **kwargs): # real signature unknown读取指定字节数据passdef readable(self, *args, **kwargs): # real signature unknown是否可读passdef readline(self, *args, **kwargs): # real signature unknown仅读取一行数据passdef seek(self, *args, **kwargs): # real signature unknown指定文件中指针位置passdef seekable(self, *args, **kwargs): # real signature unknown指针是否可操作passdef tell(self, *args, **kwargs): # real signature unknown获取指针位置passdef truncate(self, *args, **kwargs): # real signature unknown截断数据,仅保留指定之前数据passdef writable(self, *args, **kwargs): # real signature unknown是否可写passdef write(self, *args, **kwargs): # real signature unknown写内容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultclosed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultencoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaulterrors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultline_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultname = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultnewlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x

class file(object)def close(self): # real signature unknown; restored from __doc__关闭文件"""close() -> None or (perhaps) an integer.  Close the file.Sets data attribute .closed to True.  A closed file cannot be used forfurther I/O operations.  close() may be called more than once withouterror.  Some kinds of file objects (for example, opened by popen())may return an exit status upon closing."""def fileno(self): # real signature unknown; restored from __doc__文件描述符  """fileno() -> integer "file descriptor".This is needed for lower-level file interfaces, such os.read()."""return 0    def flush(self): # real signature unknown; restored from __doc__刷新文件内部缓冲区""" flush() -> None.  Flush the internal I/O buffer. """passdef isatty(self): # real signature unknown; restored from __doc__判断文件是否是同意tty设备""" isatty() -> true or false.  True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__获取下一行数据,不存在,则报错""" x.next() -> the next value, or raise StopIteration """passdef read(self, size=None): # real signature unknown; restored from __doc__读取指定字节数据"""read([size]) -> read at most size bytes, returned as a string.If the size argument is negative or omitted, read until EOF is reached.Notice that when in non-blocking mode, less data than what was requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__读取到缓冲区,不要用,将被遗弃""" readinto() -> Undocumented.  Don't use this; it may go away. """passdef readline(self, size=None): # real signature unknown; restored from __doc__仅读取一行数据"""readline([size]) -> next line from the file, as a string.Retain newline.  A non-negative size argument limits the maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef readlines(self, size=None): # real signature unknown; restored from __doc__读取所有数据,并根据换行保存值列表"""readlines([size]) -> list of strings, each a line from the file.Call readline() repeatedly and return a list of the lines so read.The optional size argument, if given, is an approximate bound on thetotal number of bytes in the lines returned."""return []def seek(self, offset, whence=None): # real signature unknown; restored from __doc__指定文件中指针位置"""seek(offset[, whence]) -> None.  Move to new file position.Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1(move relative to current position, positive or negative), and 2 (moverelative to end of file, usually negative, although many platforms allowseeking beyond the end of a file).  If the file is opened in text mode,only offsets returned by tell() are legal.  Use of other offsets causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__获取当前指针位置""" tell() -> current file position, an integer (may be a long integer). """passdef truncate(self, size=None): # real signature unknown; restored from __doc__截断数据,仅保留指定之前数据"""truncate([size]) -> None.  Truncate the file to at most size bytes.Size defaults to the current file position, as returned by tell()."""passdef write(self, p_str): # real signature unknown; restored from __doc__写内容"""write(str) -> None.  Write string str to file.Note that due to buffering, flush() or close() may be needed beforethe file on disk reflects the data written."""passdef writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__将一个字符串列表写入文件"""writelines(sequence_of_strings) -> None.  Write the strings to the file.Note that newlines are not added.  The sequence can be any iterable objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__可用于逐行读取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass

2.x

a = open("5.log","r+",encoding="utf-8")
# a.truncate()     #依赖于指针,截取数据,只剩下指针所在位置的前面的数据
# a.close()        #关闭
# a.flush()        #强行加入内存
# a.read()         #读
# a.readline()     #只读取第一行
# a.seek(0)        #指针
# a.tell()         #当前指针位置
# a.write()        #写

c、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:pass

例:

#关闭文件with
with open("5.log","r") as a:a.read()#同事打开两个文件,把a复制到b中,读一行写一行,直到写完
with open("5.log","r",encoding="utf-8") as a,open("6.log","w",encoding="utf-8") as b:for line in a:b.write(line)

lambda表达式


学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

# 普通条件语句
if 1 == 1:name = 'wupeiqi'
else:name = 'alex'# 三元运算
name = 'wupeiqi' if 1 == 1 else 'alex'

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

# ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):return arg + 1# 执行函数
result = func(123)# ###################### lambda ####################### 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1# 执行函数
result = my_lambda(123)

递归

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368…

def func(arg1,arg2):if arg1 == 0:print arg1, arg2arg3 = arg1 + arg2print arg3func(arg2, arg3)func(0,1)def func(n,a,b):if n == 10:return ac = a + breturn func(n+1,b,c)ret = func(1,0,1)
print(ret)# 列出一组数据
a,b = 0,1
while b <1000:print(a)a, b = b, a+ b

冒泡排序

# li = [11,2,35,14,22,35235,1232141,345,321423,123,123234]
# for j in range(1,len(li)):
#     for i in range(len(li)-j):
#         if li[i]<li[i+1]:
#             temp = li[i]
#             li[i]=li[i+1]
#             li[i+1]=temp
# print(li)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/38651.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

redis-数据类型及样例

一.string 类型数据的基本操作 1.添加/修改数据 set key value2.获取数据 get key3.删除数据 del key4.添加/修改多个数据 mset key1 value1 key2 value25.获取多个数据 mget key1 key2二.list类型的基本操作 数据存储需求&#xff1a;存储多个数据&#xff0c;并对数据…

day 0815

计算文件有多少行&#xff1f; 2.文件的拷贝

SpringBoot引入外部jar打包失败解决,SpringBoot手动引入jar打包war后报错问题

前言 使用外部手动添加的jar到项目&#xff0c;打包时出现jar找不到问题解决 处理 例如项目结构如下 引入方式换成这种 <!-- 除了一下这两种引入外部jar&#xff0c;还是可以将外部jar包添加到maven中&#xff08;百度查&#xff09;--><!-- pdf转word --><…

前端代理配置

dev: {env: require(./dev.env),port: process.env.PORT || 8080,autoOpenBrowser: true,assetsSubDirectory: static,assetsPublicPath: /,proxyTable: {// 以 /party/fundamental/ 开头的请求&#xff0c;全部转发到 target 设置的地址/party/fundamental/: {// target: http…

Windows下升级jdk1.8小版本

1.首先下载要升级jdk最新版本&#xff0c;下载地址&#xff1a;Java Downloads | Oracle 中国 2.下载完毕之后&#xff0c;直接双击下载完毕后的文件&#xff0c;进行安装。 3.安装完毕后&#xff0c;调整环境变量至新安装的jdk位置 4.此时&#xff0c;idea启动项目有可能会出…

ATF bl1 ufshc_dme_get/set处理流程分析

ATF bl1 ufshc_dme_get/set处理流程分析 UFS术语缩略词1 ATF的下载链接2 ATF BL1 ufshc_dme_get/set流程3 ufs总体架构图3.1 UFS Top Level Architecture3.2 UFS System Model 4 ufshc_dme_get/set函数接口详细分析4.1 ufshc_dme_get4.2 ufshc_dme_set4.3 ufshc_send_uic_cmd4.…

nodejs+vue+elementui考研互助交流网站

语言 node.js 框架&#xff1a;Express 前端:Vue.js 数据库&#xff1a;mysql 数据库工具&#xff1a;Navicat 开发软件&#xff1a;VScode 前端nodejsvueelementui,该系统采用vue技术和B/S结构进行开发设计&#xff0c;后台使用MySQL数据库进行数据存储。系统主要分为两大模…

java面试题(16):Mysql一致性视图是啥时候建立的

1 演示错误案例 先给大家来一个错误演示。 我们打开两个会话窗口&#xff0c;默认情况下隔离级别是可重复读&#xff0c;我们来看下&#xff1a; 首先在 A 会话中查看当前 user 表&#xff0c;查看完成后开启事务&#xff1a; 可以看到id3的数据sex是男。 接下来在 B 会话中…

K8S系列一:概念入门

写在前面 本文组织方式&#xff1a; K8S的架构、作用和目的。需要首先对K8S整体有所了解。 K8S是什么&#xff1f; 为什么是K8S&#xff1f; K8S怎么做&#xff1f; K8S的重要概念&#xff0c;即K8S的API对象。要学习和使用K8S必须知道和掌握的几个对象。 Pod 实例 Volume 数…

php错误类型与处理

1 语法编译错误&#xff0c;少了分号&#xff0c;这是系统触发的错误&#xff0c;不需要我们去管。 2 错误类型有四种&#xff1a;error致命错误&#xff0c;代码不会往下运行&#xff1b;warning&#xff1a;提醒错误&#xff0c;会往下运行&#xff0c;但是会有意想不到的结果…

【C++学习】STL容器——stack和queue

目录 一、stack的介绍和使用 1.1 stack的介绍 1.2 stack的使用 1.3 stack的模拟实现 二、queue的介绍和使用 2.1 queue的介绍 2.2 queue的使用 2.3 queue的模拟实现 三、priority_queue的介绍和使用 3.1 priority_queue的介绍和使用 3.2 priority_queue的使用 3.4 p…

JVM---理解jvm之对象已死怎么判断?

目录 引用计数算法 什么是引用 可达性分析算法&#xff08;用的最多的&#xff09; 引用计数算法 定义&#xff1a;在对象中添加一个引用计数器&#xff0c;每当有一个地方引用它时&#xff0c;计数器值就加一&#xff1b;当引用失效时&#xff0c;计数器值就减一&#xff1…

国内外医疗器械政策法规网站集合

随着医疗技术的不断发展&#xff0c;医疗器械在现代医疗中扮演着重要的角色。为了确保医疗器械的安全性、有效性和质量&#xff0c;各国纷纷制定了一系列的政策法规来监管医疗器械的研发、生产、销售和使用。这些政策法规的制定和实施对于保障公众健康、促进医疗器械产业的健康…

旧版本docker未及时更新,导致更新/etc/docker/daemon.json配置文件出现docker重启失败

一、背景 安装完docker和containerd之后&#xff0c;尝试重启docker的时候&#xff0c;报错如下&#xff1a; systemctl restart dockerJob for docker.service failed because the control process exited with error code. See “systemctl status docker.service” and “…

学习ts(一)数据类型(基础类型和任意类型)

运行 起步安装 npm install typescript -g 运行tsc index.ts生成对应的js文件&#xff0c;然后使用node index.js执行js文件 为了方便运行还可以安装插件&#xff0c;ts-node index.ts运行即可 npm i ts-node -g npm init -y npm i types/node -D基本数据类型 // 1.字符…

ARM(汇编指令)

.global _start _start:/*mov r0,#0x5mov r1,#0x6 bl LoopLoop:cmp r0,r1beq stopsubhi r0,r0,r1subcc r1,r1,r0mov pc,lr*/ mov r0,#0x1mov r1,#0x0mov r2,#0x64bl Loop Loop:cmp r0,r2bhi stopadd r1,r1,r0add r0,r0,#0x01mov pc,lr stop:B stop.end

现有的vue3+ts+vite项目集成electron

效果图 什么时Electron Electron是使用JavaScript,HTML和CSS构建跨平台的桌面应用程序框架。 Electron兼容Mac、Windows和Linux,可以构建出三个平台的应用程序。 现有的vue3项目集成Electron 安装依赖 原来有一个vue3+ts+vite+pnpm的项目,其中sub-modules是子项目,web是…

Monge矩阵

Monge矩阵 对一个m*n的实数矩阵A&#xff0c;如果对所有i&#xff0c;j&#xff0c;k和l&#xff0c;1≤ i<k ≤ m和1≤ j<l ≤ n&#xff0c;有 A[i,j]A[k,l] ≤ A[i,l]A[k,j] 那么&#xff0c;此矩阵A为Monge矩阵。 换句话说&#xff0c;每当我们从矩阵中挑…

全面梳理Python下的NLP 库

一、说明 Python 对自然语言处理库有丰富的支持。从文本处理、标记化文本并确定其引理开始&#xff0c;到句法分析、解析文本并分配句法角色&#xff0c;再到语义处理&#xff0c;例如识别命名实体、情感分析和文档分类&#xff0c;一切都由至少一个库提供。那么&#xff0c;你…

地理数据的双重呈现:GIS与数据可视化

前一篇文章带大家了解了GIS与三维GIS的关系&#xff0c;本文就GIS话题带大家一起探讨一下GIS和数据可视化之间的关系。 GIS&#xff08;地理信息系统&#xff09;和数据可视化在地理信息科学领域扮演着重要的角色&#xff0c;它们之间密切相关且相互增强。GIS是一种用于采集、…