1+ ## 字典合并
2+ d1 = {'a' : 'A' , 'b' : 'B' , 'c' : 'C' }
3+ d2 = {'d' : 'D' , 'e' : 'E' }
4+
5+ # 旧版
6+ d3 = {** d1 , ** d2 } # 使用展开操作符,将合并结果存入 d3
7+ print (d3 ) # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}
8+
9+ d1 .update (d2 ) # update 方法,将 d1 d2 合并,且更新 d1
10+ print (d1 ) # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}
11+
12+ # 新版
13+ d3 = d1 | d2 # 效果等同于展开操作符
14+ print (d3 ) # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}
15+
16+ d1 |= d2 # 等同于 update
17+ print (d1 ) # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}
18+
19+
20+ ## 拓扑排序
21+ from graphlib import TopologicalSorter
22+
23+ tg = {5 : {3 , 4 }, 4 : {2 , 3 }, 3 : {2 , 1 }, 2 : {1 }}
24+ ts = TopologicalSorter (tg )
25+
26+ print (list (ts .static_order ())) # [1, 2, 3, 4, 5]
27+
28+ ts = TopologicalSorter ()
29+ ts .add (5 , 3 , 4 )
30+ ts .add (4 , 2 , 3 )
31+ ts .add (3 , 2 , 1 )
32+ ts .add (2 , 1 )
33+
34+ print (list (ts .static_order ())) # [1, 2, 3, 4, 5]
35+
36+
37+ ## 随机字节码
38+ import random
39+ print (random .randbytes (10 )) # b'\x0fzf\x17K\x00\xfb\x11LF' 随机的,每次结果可能不同
40+
41+
42+ ## 最小公倍数
43+ import math
44+ math .lcm (49 , 14 ) # 98
45+
46+ def lcm (num1 , num2 ):
47+ if num1 == num2 == 0 :
48+ return 0
49+ return num1 * num2 // math .gcd (num1 , num2 )
50+
51+ lcm (49 , 14 ) # 98
52+
53+
54+ ## 字符串去前后缀
55+ "three cool features in Python" .removesuffix (" Python" )
56+ # three cool features in
57+
58+ "three cool features in Python" .removeprefix ("three " )
59+ # cool features in Python
60+
61+ "three cool features in Python" .removeprefix ("Something else" )
62+ # three cool features in Python
63+
64+
65+ ## 时区
66+ from zoneinfo import ZoneInfo
67+ from datetime import datetime
68+
69+ dt = datetime (2020 , 10 , 1 , 1 , tzinfo = ZoneInfo ("America/Los_Angeles" ))
0 commit comments