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

Python:从首个列表随机抽取元素后如何获取第二个列表的对应内容(需代码示例)

可运行Python实现方案

方案1:按要求新增stats列表(索引对应模式)

  • 逻辑说明:保持sales列表与stats列表元素顺序一一对应,通过随机生成索引值的方式同时获取商品和对应属性,完全符合新增stats列表的需求
import random

# 原有商品列表
sales = ["coke can", "pot of instant noodles", "chocolate bar", "lottery ticket"]
# 新增属性列表,与sales列表顺序一一对应
stats = ["heals 25hp", "restores 40 satiety", "boosts 15 mood", "may trigger random reward"]

# 生成随机索引,保证商品和属性匹配
random_index = random.randint(0, len(sales) - 1)
selected_item = sales[random_index]
selected_item_stat = stats[random_index]

# 输出结果
print(f"A {selected_item} catches your eye. Effect: {selected_item_stat}")

方案2:字典关联模式(更易维护,推荐使用)

  • 逻辑说明:用字典直接绑定商品和对应属性,不需要手动维护两个列表的顺序匹配,后续新增/删除商品时不会出现属性错位问题
import random

# 商品与属性直接关联存储
item_map = {
    "coke can": "heals 25hp",
    "pot of instant noodles": "restores 40 satiety",
    "chocolate bar": "boosts 15 mood",
    "lottery ticket": "may trigger random reward"
}

# 随机抽取商品及对应属性
selected_item, selected_stat = random.choice(list(item_map.items()))

# 输出结果
print(f"A {selected_item} catches your eye. Effect: {selected_stat}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:45:02