Python 笔记

Table of Contents

常用代码

判断文件是否存在

import os
os.path.exists("test_file.txt")

读取缓存文件并保存

import json
import os
cache_file = "cache.json"
cache = {}
if os.path.isfile(cache_file):
    with open(cache_file) as f:
        cache = json.load(f)
with open(cache_file, 'w', encoding='utf-8') as f:
    json.dump(cache, f, ensure_ascii=False, indent=4)

Python Tips

4. Map, Filter and Reduce

https://book.pythontips.com/en/latest/map_filter.html

items_4_1 = [1, 2, 3, 4, 5]
squared_4_1 = list(map(lambda x: x**2, items_4_1))
print("\nMap: 所有元素求平方\n  old: ", items_4_1, "\n  new: ", squared_4_1)

number_list_4_2 = list(range(-5, 5))
less_than_zero_4_2 = list(filter(lambda x: x < 0, number_list_4_2))
print("\nFilter: 保留小于零\n  old: ", number_list_4_2, "\n  new: ", less_than_zero_4_2)

from functools import reduce
items_4_3 = [1, 2, 3, 4]
product_4_3 = reduce((lambda x, y: x * y), items_4_3)
print("\nReduct: 所有元素累乘\n  old: ", items_4_3, "\n  new: " + str(product_4_3))

Author: Saul Lawliet

Created: 2022-02-22 Tue 20:43