lambda函数是一种表达式,创建内嵌的简单匿名函数
lambda n: n%2!=0 # 相当于函数 def function(n): return n%2!=0返回一个列表,其中包含对其执行函数时结果为真的所有元素
Filter filter(function,seq)
filter函数的function返回布尔值,根据布尔值过滤
list=[1,2,3,4,5,6,7,8,] result=[] for i in range(0,len(list)): if list[i]%2!=0: result.append(list[i]) result --> [1, 3, 5, 7] ########################################### result=filter(lambda n: n%2!=0,[1,2,3,4,5,6,7,8,]) result --> <filter object at 0x000002C585F16CA0> list(result) --> [1, 3, 5, 7]创建一个列表,其中包含对指定序列包含的项执行指定函数返回的值
Map map(function,sequence,....)
map函数返回一些列运算或操作的结果值
list=[1,2,3,4,5,6,7,8,9] result=[] for i in range(0,len(list)): result.append(list[i]*list[i]) result --> [1, 4, 9, 16, 25, 36, 49, 64, 81] ########################################### result=map(lambda n: n*n,[1,2,3,4,5,6,7,8,9]) result --> <map object at 0x00000230AD12D5F8> list(result) --> [1, 4, 9, 16, 25, 36, 49, 64, 81]使用指定的函数将序列的前两个元素合二为一,再将结果与第三元素合二为一,依此类推,直到处理完整个序列并得到一个结果
Reduce reduce(func,sequence[,initial])
reduce中m为前面结果,n为下一个
list=[1,2,3,4,5,6,7,8,9] result=0 for i in range(0,len(list)): result+=list[i] result --> 45 ######################################## from functools import reduce result=reduce(lambda m,n:m+n,[1,2,3,4,5,6,7,8,9]) result --> 45File open(file_path[,mode,encoding])
void File.close()
打开关闭要异常处理
with自动关闭文件,存在异常也会自动关闭 with open(file_path[,mode,encoding] as f: \n #do-somthing)
file=open("D:\copy.txt") file --> <_io.TextIOWrapper name='D:\\copy.txt' mode='r' encoding='cp936'> file.close() ######################## with open("D:\copy.txt") as f: print(f) Result: <_io.TextIOWrapper name='D:\\copy.txt' mode='r' encoding='cp936'>String File.read([character_num]) --> 读取全部或character_num
int File.seek([character_num]) --> 向前移动character_num位
String File.readline([character_num]) --> 读取一行或一行中character_num
List File.readlines() --> 按行读取全部,并将每行放入List
# txt This is a test This is a test ############################### file=open('D:\\test.txt',encoding="utf-8") file.read(4) --> 'This' file.seek(4) --> 4 file.read() --> ' is a test\n\nThis is a test' file.close() ############################### file=open('D:\\test.txt',encoding="utf-8") file.readline() --> 'This is a test\n' file.readline(4) --> '\n' ############################### file=open('D:\\test.txt',encoding="utf-8") file.readlines() --> ['This is a test\n', '\n', 'This is a test']int File.write()
void File.writelines(sequence_date)
# txt This is a test This is a test ############################### file=open('D:\\test.txt','w',encoding="utf-8") file.write("\nThis is a test") --> 15 file.close() ############################### # txt This is a test ############################### file=open('D:\\test.txt','a',encoding="utf-8") file.writelines(["\nadd first line\n","\n","add second line"]) file.close() ############################### # txt This is a test add first line add second line