You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中高效解析第三方Leg数据并判定旅行类型的方案探讨

解析Leg行程数据并判定旅行类型的优化方案

别用一堆if/else硬怼,先把数据标准化、构建清晰的路径,再基于路径特征做判定,代码会更简洁易维护。

步骤1:按时间排序Leg数据

第三方返回的Leg不一定按时间顺序排列,第一步必须先排序,否则路径逻辑会乱。先把时间字符串转成可比较的格式:

from datetime import datetime

def parse_time(time_str):
    # 处理12小时制时间(如示例中的'2:00'),转成可排序的time对象
    return datetime.strptime(time_str, '%I:%M').time()

def sort_legs_by_time(legs):
    return sorted(legs, key=lambda x: parse_time(x['StartTime']))

步骤2:构建完整路径并验证连续性

把排序后的Leg串成完整路径,同时检查路段间的衔接是否合法(避免数据异常):

def build_trip_path(sorted_legs):
    if not sorted_legs:
        return [], False
    
    path = [sorted_legs[0]['Origin']]
    is_continuous = True
    
    for idx, leg in enumerate(sorted_legs):
        # 从第二个路段开始,检查当前起点是否等于前一段的终点
        if idx > 0 and leg['Origin'] != path[-1]:
            is_continuous = False
        path.append(leg['Destination'])
    
    return path, is_continuous

步骤3:基于路径判定旅行类型

根据路径的首尾节点、路段数量,就能清晰分类:

def determine_trip_type(path, is_continuous, leg_count):
    if not is_continuous:
        return "异常行程(路径不连续)"
    
    start_loc = path[0]
    end_loc = path[-1]
    
    if start_loc != end_loc:
        return "单程(单路段)" if leg_count == 1 else "多站点单程"
    else:
        return "往返(双路段)" if leg_count == 2 else "多站点往返"

整合使用示例

把上面的函数串起来,测试你的示例数据:

# 示例1:往返行程
legs_example1 = [
    {'Origin': 'location1', 'StartTime': '12:00', 'Destination': 'location2', 'EndTime': '2:00'},
    {'Origin': 'location2', 'StartTime': '4:00', 'Destination': 'location1', 'EndTime': '6:00'}
]
sorted_legs = sort_legs_by_time(legs_example1)
path, continuous = build_trip_path(sorted_legs)
print(determine_trip_type(path, continuous, len(sorted_legs)))  # 输出:往返(双路段)

# 示例2:多站点往返行程
legs_example2 = [
    {'Origin': 'location1', 'StartTime': '12:00', 'Destination': 'location2', 'EndTime': '2:00'},
    {'Origin': 'location2', 'StartTime': '4:00', 'Destination': 'location3', 'EndTime': '6:00'},
    {'Origin': 'location3', 'StartTime': '12:00', 'Destination': 'location1', 'EndTime': '2:00'}
]
sorted_legs = sort_legs_by_time(legs_example2)
path, continuous = build_trip_path(sorted_legs)
print(determine_trip_type(path, continuous, len(sorted_legs)))  # 输出:多站点往返

为什么这方案更好?

  1. 逻辑分层清晰:排序→建路径→判类型,每一步只做一件事,出问题好定位
  2. 扩展性强:如果以后要新增旅行类型(比如循环行程),只需在判定函数里加分支,不用改动前面的逻辑
  3. 自动处理异常:直接标记路径不连续的异常行程,避免后续逻辑出错

对于你提到的4段行程场景:

  • 若路径是A→B→C→D→A,会判定为多站点往返
  • 若路径是A→B→C→D→E,会判定为多站点单程
  • 若路径是A→B→A→B→A,同样判定为多站点往返,完全符合业务逻辑

内容的提问来源于stack exchange,提问作者Ecornwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:25:15