Python 开发中使用的函数总结
1、lambda匿名函数
time_list = [{"year": 2021, "month": 5, "day": 20}, {"year": 2021, "month": 5, "day": 21}]
# 使用lambda 函数对字典s中的value以元组的形式添加到列表n中
time_group = lambda s, n: n.append((s.get('year'), s.get('month'), s.get('day')))
s_list = []
# 循环遍历time_list
[time_group(i, s_list) for i in list(time_list )]
# 输出处理后的结果
print(s_list)
2、sorted() 排序
sorted(iterable, key=None, reverse=False)
# list()转换为列表, set() 集合去重
sorted(list(set(s_list)))
# zfill()自动补充0将字符串的位数改为2位数
sorted(dict_, key=lambda x: '-'.join(
[str(x['year']),
[str(x['month']).zfill(2),
[str(x['day']).zfill(2)
]))
3、filter()
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = filter(lambda x: x % 2 == 1, example_list)
print(list(result_list))
输出
"C:\Program Files\Python39\python.exe" E:/caicai/tests.py
[5, 1, 7, 3]
Process finished with exit code 0
4、Interval()
"""
Interval是一个区间库,可以给出范围值判断是否在范围中
"""
from interval import Interval
time_ = time.strftime("%H:%m")
if time_ in Interval("15:00", "16:00"):
print("Now time is ", time_)
"C:\Program Files\Python39\python.exe" E:/caicai/tests.py
Now time is 15:05
Process finished with exit code 0
5、ast.literal_eval()
"""将字符串带有字典列表的关键符号进行转换"""
import ast
dict_ = ast.literal_eval('{"name":"Bob"}')
print(dict_)
print(type(dict_))
print(isinstance(dict_, dict))
"C:\Program Files\Python39\python.exe" E:/caicai/tests.py
{'name': 'Bob'}
<class 'dict'>
True
Process finished with exit code 0