本周阅读摘选
2024-12-02 → 2024-12-08
目录
学术相关
Data-driven reliable facility location design
技术技巧
Python丨微信与定时任务
wxauto
库基于UIAutomation的开源python微信自动化库
sched
标准库模块,基于事件的定时调度器
APSchedular
库,支持多种调度方式,如定时任务、周期任务,支持cron
表达式
dict.get()默认值
通过带有默认值的dict.get()
方法,可以避免检查键是否存在。
1
| value = my_dict.get('key', 'default')
|
字典计数器
collections.defaultdict()
1
2
3
4
5
6
7
| from collections import defaultdict
counter = defaultdict(int)
items = ['a', 'b', 'c', 'a', 'b', 'a']
for item in items:
counter[item] += 1
prprint(counter)
|
collections.Counter()
1
2
3
| from collections import Counter
counter = Counter(items)
print(counter)
|
合并字典
1
2
3
4
5
| a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
merged = {**a, **b}
# python 3.9+
merged = a | b
|
setdefault()仅当键不存在时赋值
1
| my_dict.setdefault('key', 'default') # Adds 'key' if not present
|
sorted()对字典按键或值排序
1
2
| sorted_by_key = dict(sorted(my_dict.items()))
sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1]))
|
列表创建字典
1
2
3
| keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
|