如何编写调用traffic_intensity函数统计指定交通强度天数的函数?
实现指定交通强度天数统计的解决方案
嘿,我看你正在搭建交通强度相关的统计功能,先帮你把没写完的traffic_intensity函数补全完整,再实现你需要的统计天数的核心函数~
首先补全强度判断的逻辑(我按照常见的交通流量划分补全了剩余等级,你可以根据实际需求调整阈值):
def traffic_intensity(count): """Returns string indicating intensity level given by number of vehicles""" if count < 5000: return "Very Low" elif 5000 <= count < 10000: return "Low" elif 10000 <= count < 18000: return "Medium" elif 18000 <= count < 25000: return "High" else: return "Very High"
接下来是你需要的核心函数——我给它起名叫count_days_by_target_intensity,它接收元组列表(每个元组包含日期和当日车辆数,比如("2024-01-01", 4500))和目标强度,返回匹配的天数:
def count_days_by_target_intensity(traffic_records, target_level): """ Counts how many days have the specified traffic intensity. Args: traffic_records (list of tuples): Each tuple holds (date, daily_vehicle_count) target_level (str): The intensity you want to count (e.g., "Medium") Returns: int: Number of days that match the target intensity """ matching_days = 0 # 遍历每条记录,提取车辆数并判断强度 for _, vehicle_num in traffic_records: current_level = traffic_intensity(vehicle_num) if current_level == target_level: matching_days += 1 return matching_days
用示例数据测试一下
比如你有这样的测试数据:
sample_traffic = [ ("2024-05-01", 4200), ("2024-05-02", 9500), ("2024-05-03", 16000), ("2024-05-04", 22000), ("2024-05-05", 30000), ("2024-05-06", 13000) ] # 统计"Medium"强度的天数 print(count_days_by_target_intensity(sample_traffic, "Medium")) # 输出:2
一些小优化建议
- 如果你的元组结构和示例不同(比如车辆数在第一个位置),只需要调整循环里的解构就行,比如
for vehicle_num, _ in traffic_records: - 可以给函数加上类型提示,让代码更清晰,比如
def traffic_intensity(count: int) -> str: - 要是需要一次性统计所有强度的天数,可以改成返回一个字典,键是强度等级,值是对应天数,这样用起来更灵活~
内容的提问来源于stack exchange,提问作者user9644895
相关产品推荐
相关产品推荐

