Python中存储日志正则匹配的状态关联数值应采用何种数据结构?
Hey there! Let's break down the best Python data structures for your log parsing use case—since you need to store status paths with their corresponding num1/num2/num3 values and make calculations easy, here are your top options:
1. Dictionary + Tuple/List
This is the most straightforward and efficient choice if you need to quickly look up data by the status path (like /status1). Use a tuple if your num values won't change (immutable, safer for fixed data) or a list if you need to update values later.
# Immutable version with tuples status_data = { '/status1': (10, 20, 30), '/status2': (15, 25, 35), '/status3': (5, 15, 25) } # Access num2 of /status1 print(status_data['/status1'][1]) # Output: 20 # Mutable version with lists (if you need to edit values) status_data_list = { '/status1': [10, 20, 30], '/status2': [15, 25, 35], '/status3': [5, 15, 25] } status_data_list['/status1'][0] = 12 # Update num1 for /status1
2. Dictionary + Dataclass
If you want your code to be more readable (no magic indexes like [0] or [1]), use a dataclass to give each num value a clear name. This is great for larger projects or when you need to do complex calculations—you'll avoid confusion about which index corresponds to which num.
from dataclasses import dataclass @dataclass class StatusMetrics: num1: int num2: int num3: int status_data = { '/status1': StatusMetrics(10, 20, 30), '/status2': StatusMetrics(15, 25, 35), '/status3': StatusMetrics(5, 15, 25) } # Access num3 of /status2 directly by name print(status_data['/status2'].num3) # Output: 35 # Example calculation: sum all num1 values across statuses total_num1 = sum(metric.num1 for metric in status_data.values()) print(total_num1) # Output: 30
3. List of Lists/Tuples
If you don't need fast lookups by status path and prefer to iterate through all entries, a nested list works. Just note that finding a specific status requires looping through the list, which is less efficient for large datasets.
status_data = [ ['/status1', 10, 20, 30], ['/status2', 15, 25, 35], ['/status3', 5, 15, 25] ] # Find num2 of /status3 for entry in status_data: if entry[0] == '/status3': print(entry[2]) # Output: 15 break
Final Recommendation
For most cases, go with Dictionary + Tuple (if data is fixed) or Dictionary + Dataclass (for readability). Both make accessing and calculating values a breeze, and they align perfectly with your need to map each status path to its three numerical values.
内容的提问来源于stack exchange,提问作者Lavrentijs L

