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

如何将使用random模块的while循环生成的随机结果存入变量以便复用

完全可以实现,你只需要调整原有函数的逻辑,把仅打印闪卡的逻辑改为先将抽取到的闪卡存入列表再返回,就能将结果存储到变量中随时复用。同时原有代码还有两处可以同步优化的问题:

  1. random.randint(0, len(flashcards)) 会生成等于闪卡字典长度的索引,触发KeyError报错,因为你的闪卡键是从flash_0到flash_{长度-1}的序列
  2. 原有随机抽取逻辑可能抽到重复闪卡,不符合你需要5个不同结果的要求

改进后可复用抽取结果的完整代码

import random
import time

# 你的闪卡字典示例,可替换为你的完整100组数据
flashcards = {"flash_0" : {"vecka (n)": "week"},
              "flash_1" : {"år (n)": "year"},
              "flash_2" : {"idag (adv)": "today"},
              "flash_3" : {"imorgon (adv)": "tomorrow"},
              "flash_4" : {"igår (adv)": "yesterday"},
              "flash_5" : {"kalender (n)": "calendar"},
              # 剩余94组闪卡省略
              }

def get_and_display_cards(count=5):
    # 无重复抽取指定数量的合法索引,保证5个结果不重复
    random_indexes = random.sample(range(len(flashcards)), count)
    selected_cards = []
    for idx in random_indexes:
        time.sleep(3)
        card_key = f"flash_{idx}"
        current_card = flashcards[card_key]
        # 保留原有打印效果
        print("")
        print(current_card)
        # 将闪卡存入列表用于后续复用
        selected_cards.append(current_card)
    # 返回抽取到的闪卡组合
    return selected_cards

# 调用函数时直接将结果存入自定义变量
my_selected_cards = get_and_display_cards()

结果复用示例

你可以在代码任意位置调用my_selected_cards变量使用这组闪卡:

# 遍历所有抽取到的闪卡
for card in my_selected_cards:
    # 取出单张闪卡的单词和翻译
    swedish_word = list(card.keys())[0]
    translation = list(card.values())[0]
    print(f"单词:{swedish_word},释义:{translation}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:07