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

如何在带索引的for循环中解包字典,关联产品与对应颜色

解决方案

核心思路是利用product和color列表的索引对应关系:两个列表的元素一一对应,原代码用enumerate(..., 1)获取了从1开始的索引i,对应的color元素索引为i-1(列表本身从0开始索引)。

修改后的完整代码如下:

my_dict = {"brand": "A", "product": ["X", "Y", "Z"], "color": ["red", "green", "blue"]}


def my_fnc(product, index, color):
    print(f"Product {product} at index {index} is colored {color}")


if __name__ == "__main__":
    for i, product in enumerate(my_dict["product"], 1):
        # 通过i-1获取对应位置的color值
        color = my_dict["color"][i-1]
        my_fnc(product, i, color)

运行后输出结果:

Product X at index 1 is colored red
Product Y at index 2 is colored green
Product Z at index 3 is colored blue

补充说明

  • 完全保留了原代码中enumerate(my_dict["product"], 1)的索引获取方式,确保索引从1开始计数
  • 无需遍历my_dict.items(),直接通过列表索引关联product和color即可实现需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:00