Python之路第三天,基础(3)-set,函数,内置函数,文件,三元运算,lambda

mac2022-06-30  92

set集合

集合是一个无序的,不重复的元素集合。

集合的创建:

name_set = {'tom','jerry','alex','rose'} 或 name_set = set(['tom','jerry','alex','rose'])

集合的方法:

添加一个元素 def add(self, *args, **kwargs):>>> name_set.add('jack') >>> name_set {'alex', 'tom', 'jerry', 'jack', 'rose'}

清除集合所有元素 def clear(self, *args, **kwargs):>>> name_set = {'tom','jerry','alex','rose'} >>> name_set.clear() >>> print(name_set) set()

浅拷贝 def copy(self, *args, **kwargs):>>> name_set = {'tom','jerry','alex','rose'} >>> name_set_copy = name_set.copy() >>> name_set_copy {'tom','jerry','alex','rose'}

集合A中存在,集合B中不存在的元素 def difference(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.difference(B_set) {'tom'}

从当前集合中删除和B中相同的元素 def difference_update(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.difference_update(B_set) >>> A_set {'tom'}

移除指定元素,不存在不保错 def discard(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> A_set.discard('eric') >>> A_set {'tom','jerry','jack','rose'}

移除指定元素,不存在报错 def remove(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> A_set.remove('eric') Traceback (most recent call last): File "<input>", line 1, in <module> A_set.remove('eric') KeyError: 'eric'

随机移出元素,当集合为空时报错 def pop(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> A_set.pop() 'jack' >>> A_set.pop() 'jerry' >>> A_set.pop() 'tom' >>> A_set.pop() 'rose' >>> A_set.pop() Traceback (most recent call last): File "<input>", line 1, in <module> A_set.pop() KeyError: 'pop from an empty set'

两个集合的交集 def intersection(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.intersection(B_set) {'jack', 'rose', 'jerry'}

取A,B两个集合的交集并将交集更新到A中 def intersection_update(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.intersection_update(B_set) >>> A_set {'jack', 'rose', 'jerry'}

A,B两个集合如果没有交集,返回True,否则返回False def isdisjoint(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.isdisjoint(B_set) False

集合B是否是集合A的子序列 def issubset(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose'} >>> B_set.issubset(A_set) True

集合A是否是集合B的父序列 def issuperset(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose'} >>> A_set.issuperset(B_set) True

对称差集 def symmetric_difference(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.symmetric_difference(B_set) {'tom', 'eric'}

对称差集,并更新到A中 def symmetric_difference_update(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.symmetric_difference_update(B_set) >>> A_set {'eric', 'tom'}

并集 def union(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.union(B_set) {'jerry', 'jack', 'eric', 'rose', 'tom'}

更新 def update(self, *args, **kwargs):>>> A_set = {'tom','jerry','jack','rose'} >>> B_set = {'jerry','jack','rose','eric'} >>> A_set.update(B_set) >>> A_set {'jerry', 'jack', 'eric', 'rose', 'tom'}

函数

函数定义

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

函数返回值: 默认情况下如果用户不加函数返回值函数会返回None,关键字是return

例子:

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

函数的参数

普通参数默认参数动态参数

例子:

普通参数:

#name,age叫做形参(形式参数) def func(name,age): print name #'tom',18叫做实参(实际参数) func('tom',18)

默认参数:

def func(name, age = 18): print("%s:%s" %(name,age)) # 普通参数 func('tom', 19) # 使用默认参数 func('jerry') 程序结果: tom:19 jerry:18 注:默认参数需要放在参数列表最后

动态参数:

def func(*args): print args # 可将多个参数传至args,args = (11,33,4,4454,5) func(11,33,4,4454,5) # 如果传li的话arg = ([11,2,2,3,3,4,54],),*li的话args = (11,2,2,3,3,4,54) li = [11,2,2,3,3,4,54] func(*li) def func(**kwargs): print kargs # kargs = {'name':'tom','age':18} func(name='tom',age=18) # 传**li kargs = {'name':'tom', age:18, 'gender':'male'} li = {'name':'tom', age:18, 'gender':'male'} func(**li) def func(*args, **kwargs): print args print kwargs 注意:这两个形参不能调换顺序,就像默认参数必须放在形参列表最后一样。

内置函数

abs() 取绝对值>>> abs(-10) 10 >>> abs(10) 10

all() 传一个可迭代的参数,如列表,只要列表中所有的值为真返回值才为真,有一个为假返回值就为假>>> all([0,True,[1,2],{'name':'tom'}]) False >>> all([1,True,'a',[1]]) True

any() 和all()正好相反>>> any([0,False,[],{},'hello']) True >>> any([0,False,[],{},'']) False

ascii() 忘了>>> ascii('张') "'\\u5f20'"

bin() 将10进制转换成2进制(数字前面0b代表2进制)>>> bin(2) '0b10' >>> bin(10) '0b1010' >>>

oct() 将10进制转换成8进制(数字前面0o代表8进制)>>> oct(8) '0o10' >>> oct(2) '0o2'

hex() 将10进制转换成16进制(数字前0x代表16进制)>>> hex(15) '0xf' >>> hex(10) '0xa' >>> hex(9) '0x9'

bool() 返回True或False>>> bool(1) True >>> bool(0) False >>> >>> bool([]) False >>> bool([1,2]) True

bytes() 忘了>>> >>> bytes('张',encoding='gbk') b'\xd5\xc5' >>> bytes('张',encoding='utf-8') b'\xe5\xbc\xa0'

callable() 检查对象object是否可调用,像函数,类也可被调用,实例是不可被调用,除非类中声明了__call__方法>>> def func(): ... pass ... >>> callable(func) #函数是可被调用的 True >>> callable(str) #类可被调用 True >>> s = 'abcd' >>> callable(s) False >>> help

chr() 返回整数i所对应的Unicode字符(python2.7是返回整数i所对应的ASCII字符)>>> chr(65) 'A' >>>

ord() 和chr()相反。>>> ord('A') 65 >>>

compile() 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。 ```

s = "print('hello,world!')" result = compile(s,'','exec') exec(result) hello,world!

```

complex() 复数>>>

dict() 字典类>>> dic = dict() #创建一个空字典 >>> dic {} >>>

dir() 不带参数时,返回当前范围内的变量、方法和定义的类型列表; 带参数时,返回参数的属性、方法列表。 如果参数包含方法__dir__(),该方法将被调用。当参数为实例时。 如果参数不包含__dir__(),该方法将最大限度地收集参数信息>>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'dic'] >>> s = 'hello' >>> dir(s) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

divmod() 获取商和余数>>> divmod(100,2) (50, 0) >>> divmod(100,3) (33, 1) >>> divmod(120.0,7) (17.0, 1.0) >>> divmod(129.5,7) (18.0, 3.5)

enumerate() 返回一个可枚举的对象,该对象的next()方法将返回一个tuple>>> li =['a','b','c','d','e'] >>> s = enumerate(li) >>> print(list(s)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] >>> dic = dict() >>> for i,v in enumerate(li): ... dic[i] = v ... >>> dic {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

eval() 计算表达式的值>>> s = '8*8' >>> eval(s) 64

exec() 执行python代码>>> s = "print('hello,world')" >>> >>> exec(s) hello,world

filter() 过滤,筛选符合条件的值。>>>li = [10, 20, 30, 40, 50] >>>result = filter(lambda num: num > 20, li) #简单的函数可用lambda表达式代替 >>>print(list(result))

float() 将整数或数字字符串转换成浮点数>>> float(10) 10.0 >>> num = '100' >>> >>> float(num) 100.0

format() 字符串格式化>>> s = "I'm {0},{1} years old!" >>> s.format('tom',18) "I'm tom,18 years old!" >>> s = "I'm {name},{age} years old!" >>> s.format(name='tom',age=18) "I'm tom,18 years old!"

globals() 返回一个字典,字典包含范围内的所有全局变量>>> print(globals()) {'__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'v': 'e', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__package__': None, 's': "I'm {name},{age} years old!", 'dic': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}, 'li': ['a', 'b', 'c', 'd', 'e'], 'i': 4, '__name__': '__main__', '__doc__': None, 'num': '100'}

hash() 创建一个hash值>>> s = 'hello,world' >>> hash(s) 6931535528834423677

help() 查看帮助信息>>> li = [1,2,4,3] >>> >>> help(li.sort) Help on built-in function sort sort(...) method of builtins.list instance L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

id() 查看对象的内存地址>>> s = 'hello,world' >>> id(s) 139749839772464

input() 等待用户输入>>> s = input('username:') username:tom >>> >>> print(s) tom

int() 转换成整型数>>> s = '10' #将字符串强转成数字 >>> int(s) 10 >>> f = 15.3 #将浮点数转换成整型数,会损失精度 >>> int(f) 15

isinstance() 判断对象是否是某个类的实例>>> s = 'hello,world' >>> isinstance(s,str) #判断s是否是str类的实例 True >>> isinstance(s,dict) False

len() 求对象的长度或元素的个数>>> s = 'hello,world' >>> len(s) 11 >>> li = [1,2,3,4,5] >>> len(li) 5 >>> t = (1,2,3,4,5) >>> len(t) 5

list() 创建列表或转换成列表>>> li = list() #创建一个空列表 >>> li []

locals() 查看所有局部变量>>>

map() 此函数有两个参数,第一个是函数名,第二个是可迭代的对象。遍历每个元素,执行function操作>>> li = [10,20,30,40,50] >>> result = map(lambda num:num+100,li) >>> print(list(result)) [110, 120, 130, 140, 150]

max() 求最大值,参数可以传一个可迭代的对象,如列表,返回最大的元素;如果是两个或两个以上的参数,返回最大的那一个>>> max(10,20,40,60) #传多个参数 60 >>> li = [10,20,40,50] #传一个列表 >>> max(li)

min() 求最小值,参数和max()一样,返回最小的那个元素或值>>> li = [10,20,40,50] >>> min(li) 10 >>> min(10,20,40,50) 10

open() 文件操作,打开文件>>> f = open('test.txt','r') #以只读的方式打开test.txt文件

pow() 求第一个参数的第二个参数次方>>> pow(2,10) 1024

print() 格式化输出函数>>> print('hello,world') hello,world >>> print("I'm %s,%d years old" %('tom',18)) I'm tom,18 years old

range() 产生一个序列,默认从0开始>>> list(range(6)) [0, 1, 2, 3, 4, 5] >>> list(range(1,6)) [1, 2, 3, 4, 5] >>> >>> list(range(0,6,2)) [0, 2, 4]

repr() 返回一个字符串可打印对象>>>repr('hello') "'hello'"

reversed() 反转,和列表里的reversed基本一样,他会去调用列表里的resversed方法>>> li = [1,2,3,4,5] >>> reversed(li) <list_reverseiterator object at 0x7f1a0b8988d0> >>> list(reversed(li)) [5, 4, 3, 2, 1]

round() 四舍五入>>> round(5.6) 6 >>> round(5.4) 5

set() 创建一个空集合,或者转换成一个集合>>> s = set() #创建空集合 >>> s set() >>> s = set([1,2,4,4,5]) #传入一个可迭代的对象,将列表转换为集合 >>> s {1, 2, 4, 5}

slice() 切片>>>

sorted() 排序,和list类里的sort方法相似>>> li = [1,5,3,4,2] >>> sorted(li) [1, 2, 3, 4, 5] >>> li [1, 5, 3, 4, 2] >>> sorted(li,reverse=True) [5, 4, 3, 2, 1]

str() 字符串类>>> str(231) '231'

sum() 求和>>> sum([1,2,3,4,5]) #参数为可迭代的对象 15

tuple() 返回一个不可变的元组>>> t = tuple() #创建一个空元组 >>> t () >>> t = tuple([1,2,3,4,5]) #传入一个列表,将列表转换成元组 >>> t (1, 2, 3, 4, 5)

type() 查看对象数据类型>>> t (1, 2, 3, 4, 5) >>> type(t) <class 'tuple'> >>> type('hello') <class 'str'> >>> type([1,2,3,4,5]) <class 'list'>

vars() 返回对象的属性,当不加参数的时,等同locals(),当有一个参数时, 这个参数必须有__dict__属性>>>vars()

zip() 解释起来好复杂,直接看例子吧>>> li1 = [1,2,3] >>> li2 = [4,5,6] >>> zip(li1,li2) <zip object at 0x7f1a0b889048> >>> list(zip(li1,li2)) [(1, 4), (2, 5), (3, 6)]

未完待续。。。

局部变量和全局变量

局部变量 在函数字义内定义的变量为局部变量,只能在函数体内使用。 def func1(): name = 'tom' age = 18 print('I am %s,%d years old!' % (name,age)) func1() print('I am %s,%d years old!' % (name,age)) #在函数体外无法找到这两个变量 执行结果: I am tom,18 years old! Traceback (most recent call last): File "local.py", line 10, in <module> print('I am %s,%d years old!' % (name,age)) NameError: name 'name' is not defined 全局变量 在文件头定义,并且在函数体外定义的为变量为全局变量,在python中全局变量虽然没有规定大不写,但是我们约定全局变量都大写。 全局变量在函数内只能读取,不能修改,如果想要在函数内修改得在函数内加global关键字 NAME = 'jerry' AGE = 20 def func1(): NAME = 'jack' #注意,这并不是修改的全局变量,这相当于字义了一个和全局变量名字相同的局部变量 AGE = 30 name = 'tom' age = 18 print('I am %s,%d years old!' % (name,age)) print('I AM %s,%d YEARS OLD!' % (NAME,AGE)) func1() print('I am %s,%d years old!' % (NAME,AGE)) 程序结果: I am tom,18 years old! I AM jack,30 YEARS OLD! I am jerry,20 years old!

如果想在函数里修改全局变量,则需要global关键字

NAME = 'jerry' AGE = 20 def func1(): global NAME global AGE NAME = 'jack' #注意,这并不是修改的全局变量,这相当于字义了一个和全局变量名字相同的局部变量 AGE = 30 name = 'tom' age = 18 print('I am %s,%d years old!' % (name,age)) print('I AM %s,%d YEARS OLD!' % (NAME,AGE)) func1() print('I am %s,%d years old!' % (NAME,AGE)) 程序结果: I am tom,18 years old! I AM jack,30 YEARS OLD! I am jack,30 years old!

文件操作

文件操作的三个步骤:

打开文件操作文件关闭文件

操作文件的函数:

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

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

r,只读模式,如果open打开文件不指定打开模式,默认为只读模式w,只写模式,如果文件不存在则创建,存在则清空文件内容x, 只写模式,不可读;不存在则创建,存在则报错。python3中才有的,python2中没有这个方式。a, 追加模式 可读,不存在则创建;存在则只追加内容;

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

r+, 读写,可读,可写(最常用)w+,写读,可读,可写x+ ,写读,可读,可写a+, 写读,可读,可写

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

rb 或 r+bwb 或 w+bxb 或 w+bab 或 a+b

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

操作文件

操作文件的方法:

关闭文件 def close(self, *args, **kwargs):>>> f = open('test.txt','w') >>> f.close()

打开文件描述符 def fileno(self, *args, **kwargs):>>> f = open('test.txt','r') >>> f.fileno() 3

刷新文件内部缓存区 def flush(self, *args, **kwargs):>>> f = open('test.txt','w') >>> f.write('hello,world!') #这时内容还在缓存区里保存着,并没有写到磁盘上 >>> f.flush() #强刷缓存区的内容到磁盘

判断文件是否是tty设备(linux系统) def isatty(self, *args, **kwargs):>>> f = open('test.txt','w') >>> f.isatty() False

读取指定字节数据 def read(self, *args, **kwargs):>>> f = open('test.txt','r') >>> f.read(10) 'hello,worl'

是否可读 def readable(self, *args, **kwargs):>>> f = open('test.txt','w') >>> f.readable() False

仅读取一行数据 def readline(self, *args, **kwargs):>>> f = open('test.txt','r') >>> f.readline() 'hello,world!\n' >>> f.readline() 'hello,python!'

指定文件中的指针位置 def seek(self, *args, **kwargs):>>> f = open('test.txt','r') >>> f.seek(10) #移动到第10个字符 10 >>> f.read(5) #从第10个字符开始读5个字符 'd!\nhe'

指针是否可操作 def seekable(self, *args, **kwargs):>>> f = open('test.txt','a') >>> f.seekable() True

获取指针位置 def tell(self, *args, **kwargs):>>> f.close() >>> f = open('test.txt','r') >>> f.tell() 0

写内容 def write(self, *args, **kwargs):>>> f = open('test.txt','w') >>> f.write('hello,word!') 11 >>> f.close()

是否可写 def writable(self, *args, **kwargs):>>> f = open('test.txt','r') >>> f.writable() False >>> f.close() >>> f = open('test.txt','w') >>> f.writable() True >>> f.close()

管理上下文

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

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

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

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

with open('text.txt') as f1, open('text2.txt') as f2: pass

三元运算

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

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

lambda表达式

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

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

转载于:https://www.cnblogs.com/zhangxunan/p/5527094.html

最新回复(0)