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

如何从字典列表中获取随机选中字典的存储值?

核心实现方法

你存储的act1和act2都是仅包含1个键值对的字典,直接提取字典所有值的第一个元素即可拿到对应的粉丝数:

# 提取两个对象的粉丝数值
followers_1 = list(act1.values())[0]
followers_2 = list(act2.values())[0]

拿到数值之后就可以写比对逻辑了,示例判断逻辑如下:

# 校验用户答案
if (user == 1 and followers_1 > followers_2) or (user == 2 and followers_2 > followers_1) or (user == "=" and followers_1 == followers_2):
    print("回答正确!")
    score1 += 1
else:
    print("回答错误")
代码优化建议
  • 你当前用random.randrange(0,9)生成随机索引,取值范围是0到8,会漏掉列表最后一个元素,建议改成random.randrange(0,10),更简单的方法是直接用random.sample一次性抽2个不重复的对象,避免两次抽到同一个人:
act1, act2 = random.sample(names, 2)
  • 你当前用int(input(...))接收用户输入,如果用户输入=会触发类型转换报错,建议直接接收字符串类型输入,再做校验:
user = input("enter only 1,2,=").strip()
  • 也可以调整names的结构为元组列表,后续取值更方便:
names = [
    ("khloekardashian", 193),
    ("kyliejenner", 279),
    # 其余对象以此类推
]
# 取值时直接按索引取即可
act1_name, followers_1 = act1
act2_name, followers_2 = act2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:39:02