You need to enable JavaScript to run this app. Python如何查找列表特定值所有索引并按价格分组商品ID
优惠活动
大模型
产品
解决方案
定价
更多

Python如何查找列表特定值所有索引并按价格分组商品ID

实现方案

1. 无依赖纯Python实现(推荐通用场景)

直接用字典做分组适配动态新增的价格和商品,不需要提前知道价格范围,完全通用:

product_id = [40, 56, 15, 17, 12, 39, 52, 41, 14, 19, 58, 42]
price_id = [1, 9, 25, 25, 25, 1, 9, 1, 25, 25, 9, 1]

# 用字典存储 价格: 对应商品ID列表 映射
price_group = {}
for pid, price in zip(product_id, price_id):
    if price not in price_group:
        price_group[price] = []
    price_group[price].append(pid)

# 转换为目标嵌套列表格式,可按价格升序排列,不需要排序可去掉sorted
result = [[price] + pids for price, pids in sorted(price_group.items())]
print(result)
# 输出:[[1, 40, 39, 41, 42], [9, 56, 52, 58], [25, 15, 17, 12, 14, 19]]

特点:

  • 完全适配动态新增数据,新增任意价格、任意商品都不需要修改逻辑
  • 不需要引入第三方依赖,执行效率高
  • Python3.7+版本默认保持商品ID在原列表中的出现顺序,需要商品ID排序可在生成结果时对pids做sorted处理

2. 特定价格索引的获取方法

你需要的index_prod1可以直接用列表推导式生成,不需要手动循环追加:

# 获取价格为1的所有索引
index_prod1 = [idx for idx, price in enumerate(price_id) if price == 1]
# 对应生成商品列表,注意这里要取product_id对应索引的值,你之前的逻辑写反了列表
prod1 = [1] + [product_id[i] for i in index_prod1]

该方案需要提前明确所有可能的价格值,扩展性比字典分组法差,适合仅需处理少量固定价格的场景。

Pandas方案及选型建议

如果后续业务逻辑均基于DataFrame开发,有大量数据统计、过滤、关联操作,用pandas开发效率更高:

import pandas as pd

product_id = [40, 56, 15, 17, 12, 39, 52, 41, 14, 19, 58, 42]
price_id = [1, 9, 25, 25, 25, 1, 9, 1, 25, 25, 9, 1]

df = pd.DataFrame({"price": price_id, "product_id": product_id})
# 按价格分组聚合商品ID
group_df = df.groupby("price", as_index=False)["product_id"].agg(list)
# 转换为嵌套列表格式
result = group_df.apply(lambda x: [x["price"]] + x["product_id"], axis=1).tolist()

选型建议:

  • 仅需要嵌套列表做简单遍历,无其他复杂数据操作,选纯Python方案
  • 后续有复杂数据处理需求,选pandas方案,减少自定义逻辑的出错概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 07:27:02