python匿名函数 高阶函数 内置函数 文件操作

1.匿名函数

匿名就是没有名字
def func(x,y,z=1):
    return x+y+z

匿名
lambda x,y,z=1:x+y+z #与函数有相同的作用域,但是匿名意味着引用计数为0,使用一次就释放,除非让其有名字
func=lambda x,y,z=1:x+y+z 
func(1,2,3)
#让其有名字就没有意义

#有名函数与匿名函数的对比
有名函数:循环使用,保存了名字,通过名字就可以重复引用函数功能

匿名函数:一次性使用,随时随时定义

应用:map,reduce,filter

语法格式:
匿名函数 形参1,形参2,:处理逻辑

# !/usr/bin/python env
# coding:utf-8
from functools import reduce

print(list(map(lambda x: x ** 2, range(11)))) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print(reduce(lambda x, y: x * y, range(1, 11))) # 3628800

print(reduce(lambda x, y: x * y, range(1, 11),2))     # 7257600 注意reduce可以加初始值

print(list(filter(lambda x: x % 2 == 0, range(11)))) # [0, 2, 4, 6, 8, 10]

print(list(i for i in range(11) if i % 2 == 0)) # [0, 2, 4, 6, 8, 10]
map reduce filter语法格式:

关键字(函数,可迭代对象)
map 依次将可迭代对象里元素传入函数中进行逻辑处理,并输出结果
reduce 将可迭代对象里元素1,元素2传入函数中进行逻辑处理,再将结果和元素3再传入函数中进行逻辑处理,依次类推,最终输出结果
filter 遍历可迭代对象序列总每一个元素,判断每个元素布尔值,将布尔值为True的元素显示出来



2.匿内置函数

# bytes
name = "你好"
n1 = bytes(name, encoding="utf-8")
print(n1) # b'xe4xbdxa0xe5xa5xbd'
n2 = bytes(name, encoding="utf-8").decode("utf-8")
print(n2) # 你好

# chr 转为大写字母A-Z 65, 90 ord反之
print(chr(65))
print(chr(90))
# 小写字母a-z 97, 122
print(chr(97))
print(chr(122))
print(ord("z"))

# divmod 分页时用得到 100条数据 每页显示11条
print(divmod(100, 11)) # (9, 1)

# eval
dict_name = "{'name': 'z', 'age': 20}"
dict_num = "1+3+33*343"
print(eval(dict_name)) # {'age': 20, 'name': 'z'}
print(eval(dict_num)) # 11323

# hash 可hash的数据类型即不可变数据类型 不可hash的数据类型即可变变数据类型
name = "abcdef"
print(hash(name)) # 166900149

# bin hex oct 十进制转为二进制 十六进制 八进制
print(bin(10))
print(oct(100))
print(hex(100))
# 显示
# 0b1010
# 0o144
# 0x64


# isinstance 判断
print(isinstance("fds", str)) # True

# issubclass 类判断
print(issubclass(str, object)) # True str是否是object的子类



# 打印局部变量 locals
def func():
age = 1000
print(locals()) # {'age': 1000}
func()

# zip
print(list(zip(("a", "b", "c"), (1, 2, 3)))) # [('a', 1), ('b', 2), ('c', 3)]

# max min sum 求最大值 最小值 和
people = [
{'age': 123, },
{'age': 1, },
{'age': 100},
]
print(max(people, key=lambda dic: dic["age"])) # {'age': 123}

# __import__ 字符窜形式导入
# import "test" 报错 import不能导入字符串 import -->sys-->__import__
module_name = "test"
t = __import__(module_name)
t.say_hi()

3.文件操作

1.打开文件

文件句柄 = open('文件路径', encoding="utf-8",'模式')

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

打开文件的模式有:

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

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

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

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

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

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

  read       读取文件所有行 read(n) n是读几个字符

  write     写入数据

  readline 只读一行

  readlines 把每行数据生成一个列表

  wiritelines 将列表形式写入文件

  flush 内存数据写的硬盘中

  tell   显示光标所处的位置

  seek 控制光标的位置 是seek字节 seek(n,0)从0开始 seek(n,1)相对位置开始 seek(-n,2)从末尾开始

2.管理上下文

with open('log','r') as f:
  pass
 
两个文件操作
with open() as f1,open() as f2:
  pass
 
# 文件操作
with open('data_txt.txt', encoding="utf-8") as f:
with open('temp.txt', 'a', encoding="utf-8") as f1:
# 要改数据的行号
res_line = []
# 保存除去空行后的数据
del_n_data = []
data = f.readlines()
for i in data:
if len(i) > 1:
del_n_data.append(i)
for k,v in enumerate(del_n_data):
if v.startswith("zhang") and len(v) == 6:
res_line.append(k)
for i in res_line:
del_n_data[i] = "zzzzzzzzzzzzzzz "
print(del_n_data)
f1.writelines(del_n_data)


with open('data_txt.txt', 'rb') as f:
# 字符串 -->encode --> bytes
# bytes -->decode --> 字符串
data = f.read()
print(data)
print(data.decode("utf-8"))

with open('data_txt.txt', 'wb') as f:
data = "字符串1 "
f.write(bytes(data,encoding="utf-8"))
f.write(data.encode("utf-8"))

with open('data_txt.txt', 'ab') as f:
data = "字符串2 "
f.write(bytes(data,encoding="utf-8"))
f.write(data.encode("utf-8"))

# 读取文件最后一行 循环文件的推荐方式
with open('20190225.log', 'rb') as f:
for i in f:
offs = -10
while True:
f.seek(offs, 2)
data = f.readlines()
#最后一行数据+上面数据 用列表索引-1,可取到最后一行数据
if len(data) > 1:
print(data[-1].decode("utf-8"))
break
#data长度小于1,表示未读到大于一行的数据 添加offs偏移量
offs *= 2

 









原文地址:https://www.cnblogs.com/icemonkey/p/10430668.html