Última actividad 10 months ago

這段程式碼示範如何使用 Python 字典來映射數字到星期與月份名稱,並利用 _operators 列表定義一組比較運算符,以 apply_operator 函數動態執行不同類型的比較操作。適用於日期處理、數據過濾和條件判斷等應用場景。

Revisión 55d059a995577aa1bb6ee2001f81026b2a0e19b9

constants.py Sin formato
1# 定義一個字典 days,將數字對應到星期幾的名稱
2days = {
3 "1": "Monday",
4 "2": "Tuesday",
5 "3": "Wednesday",
6 "4": "Thursday",
7 "5": "Friday",
8 "6": "Saturday",
9 "7": "Sunday",
10}
11
12
13# 定義一個字典 wk_map,將數字對應到縮寫的星期幾名稱
14wk_map = {
15 "1": "Mon",
16 "2": "Tues",
17 "3": "Wed",
18 "4": "Thu",
19 "5": "Fri",
20 "6": "Sat",
21 "7": "Sun",
22}
23
24# 定義一個字典,將數字對應到縮寫的月份名稱
25months = {
26 1: "Jan",
27 2: "Feb",
28 3: "Mar",
29 4: "Apr",
30 5: "May",
31 6: "Jun",
32 7: "Jul",
33 8: "Aug",
34 9: "Sep",
35 10: "Oct",
36 11: "Nov",
37 12: "Dec",
38}
39
40
41# 定義一個二維列表 operators,包含了各種比較運算符及其對應的表示方式
42_operators = [
43 ["ge ", ">="],
44 ["le ", "<="],
45 ["lt ", "<"],
46 ["gt ", ">"],
47 ["ne ", "!="],
48 ["eq ", "="],
49 ["contains "],
50 ["datestartswith "],
51]
52
53
54# 定義一個函數來使用 operators
55def apply_operator(operator, a, b):
56 for op in _operators:
57 if operator in op:
58 if operator == "ge ":
59 return a >= b
60 elif operator == "le ":
61 return a <= b
62 elif operator == "lt ":
63 return a < b
64 elif operator == "gt ":
65 return a > b
66 elif operator == "ne ":
67 return a != b
68 elif operator == "eq ":
69 return a == b
70 elif operator == "contains ":
71 return a in b
72 elif operator == "datestartswith ":
73 return b.startswith(a)
74 return "Operator not found"
75
76
77# 檢查當前程式是否被作為主程式執行
78if __name__ == "__main__":
79 # 使用days字典將數字轉換為星期幾的名稱
80 day_number = "3"
81 day_name = days.get(day_number, "Unknown")
82 print(f"The day corresponding to number {day_number} is: {day_name}")
83
84 # 使用wk_map字典將數字轉換為縮寫的星期幾名稱
85 weekday_number = "2"
86 weekday_abbreviation = wk_map.get(weekday_number, "Unknown")
87 print(f"The abbreviation for weekday number {weekday_number} is: {weekday_abbreviation}") # fmt: skip
88
89 # 使用months字典將數字轉換為縮寫的月份名稱
90 month_number = 3
91 month_abbreviation = months.get(month_number, "Unknown")
92 print(f"The abbreviation for month number {month_number} is: {month_abbreviation}")
93
94 # 使用函數
95 print(apply_operator("ge ", 5, 3)) # True
96 print(apply_operator("lt ", 5, 3)) # False
97 print(apply_operator("contains ", "test", "this is a test")) # True
98 print(apply_operator("datestartswith ", "2024", "2024-03-22")) # True
99