Python按指定规则转换嵌套列表,实现商品区域对应数据的重组输出
实现代码
# 原始输入数组 array = [ [ "PRODUCT NAME PACK", "BAIGAM KOT", "FIAZ BAGH", "OLD ANARKALI", "SULTAN PURA", "TEZAB AAHATA", "GHORAY SHAH", "KOT KHAWAJA SAEED", ], ["002188", 0, 0, 0, 0, 0, "2", "3"], [ "PRODUCT NAME PACK", "BAGHBAN PURA", "GAWAL MANDI", "OLD ANARKALI", "MAYO HOSPITAL", "GARHI SHAHU BAZAR", "BILAL GUNJ", "LADY WELLINGTON HOSPITAL", ], ["002188", "3", 0, 0, 0, 0, 0, 0], ["008999", 0, 0, 0, 0, "1", 0, 0], ["012961", 0, 0, 0, 0, 0, "3", 0], ] result = [] index = 0 total_length = len(array) while index < total_length: current_row = array[index] # 识别城市表头行 if "PRODUCT NAME PACK" in current_row: # 提取所有城市名称(跳过表头第一个标识字段) city_list = current_row[1:] index += 1 # 处理当前表头后的所有商品数据行,直到遇到下一个表头 while index < total_length and "PRODUCT NAME PACK" not in array[index]: product_data = array[index] product_code = product_data[0] # 按索引配对城市和对应数值 for city_idx, city_name in enumerate(city_list): correspond_value = product_data[city_idx + 1] result.append([product_code, city_name, correspond_value]) index += 1 else: index += 1 # 输出最终结果 print(result)
效果说明
运行代码后输出的结果结构完全匹配需求,支持多组城市表头、多组商品数据的批量处理,你示例中给出的首段输出除笔误缺少的逗号外,和代码生成结果完全一致。
内容的提问来源于stack exchange,提问作者ArslanAli
相关产品推荐
相关产品推荐

