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

如何在书籍随机选择脚本中获取JSON列表随机项的索引?

随机选择书籍并显示对应索引的解决方案

你可以通过两种简单方式修改random_select函数,实现随机选书同时输出对应索引:

方法1:先生成随机索引,再获取对应书籍

直接生成列表范围内的随机索引,再通过索引取出书籍信息,保证索引和view_data函数的编号完全一致:

import random
import json

def random_select():
    with open(filename, "r") as f:
        temp = json.load(f)
        # 生成0到列表长度-1之间的随机索引
        random_idx = random.randint(0, len(temp)-1)
        selected_book = temp[random_idx]
        # 打印索引与书籍信息
        print(f"Index Number {random_idx}")
        print(f"Name of book: {selected_book['book']}")

方法2:用enumerate同时获取索引和元素

利用enumerate将列表转换为(索引, 元素)的元组序列,直接随机选择该序列中的元组,一步拿到索引和书籍:

import random
import json

def random_select():
    with open(filename, "r") as f:
        temp = json.load(f)
        # 将列表转为(索引, 书籍)的元组列表,再随机选择
        random_idx, selected_book = random.choice(list(enumerate(temp)))
        print(f"Index Number {random_idx}")
        print(f"Name of book: {selected_book['book']}")

原函数问题说明

你原来的random.choice(temp)仅返回列表中的单个书籍元素,不会保留它在列表中的位置信息,因此无法直接获取索引。上面两种方法都先捕获了元素的索引位置,输出逻辑和view_data完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:10:29