常用操作
排序
lambda 表达式
lambda 表达式常用于为 sorted() 函数提供自定义的排序规则。以下是一个示例,展示如何使用 lambda 表达式进行排序:
numbers = [('a', 5), ('b', 2), ('c', 8), ('d', 1)]
# 按照每个元组的第二个元素进行升序排序
sorted_numbers = sorted(numbers, key=lambda x: x[1])
print(sorted_numbers)
# 按照每个元组的第一个元素的长度进行降序排序
sorted_numbers = sorted(numbers, key=lambda x: len(x[0]), reverse=True)
print(sorted_numbers)
文件
读取文件
with open(txt_path,'r') as file:
lines = file.readlines()
for line in lines:
process(line)
但当文件过大,一次读取内存不够放入整个文件内容
使用生成器,yield关键字,yield关键字的理解看这里
def read_big_file(txt_path, chunk_size=1024*1024):
with open(txt_path,'r') as file:
while True:
chunk = file.readlines(chunk_size)
if not chunk:
break
yield chunk
for line in read_big_file('file.txt'): #创建一个生成器
process(line)
路径
Path
Path 通常指的是 pathlib 模块中的 Path 类,它提供了一种面向对象的方式来处理文件系统路径。
form pathlib import Path
p = Path('/home/user/documents.txt') # 创建实例对象
parent