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

如何修改Python代码实现随机无重复选取列表中的字典写入文件?

实现随机无重复选取字典的修改方案

要解决随机选取字典时出现重复的问题,核心是提前生成无重复的随机字典序列,而非每次循环都从完整列表中随机抽取。以下是修改后的代码及关键说明:

修改后的完整代码

#!/usr/bin/env python
import random
import shutil
from pathlib import Path

def sample() -> None:
    number_of_iteration = int(input("Enter the number of iterations for file generation\n"))
    choice_of_random = int(input("Enter 0 to run A Scenarios and 1 to run B Scenarios\n"))
    
    # 预先生成无重复的随机字典列表(仅在场景0时处理)
    random_dicts = []
    needed_dicts = [dict_1, dict_2, dict_3, dict_4, dict_5]
    if choice_of_random == 0:
        # 生成指定长度的无重复随机字典列表,若迭代次数超过字典总数,最多取全部5个
        sample_count = min(number_of_iteration, len(needed_dicts))
        random_dicts = random.sample(needed_dicts, k=sample_count)
        # 若迭代次数超过字典总数,可根据需求补充逻辑(如循环序列或提示)
    
    for i in range(1, number_of_iteration + 1):
        my_dir = Path(f"/home/user1/Iteration{i}")
        my_dir.mkdir(parents=True, exist_ok=True)
        file_name = f"file_name" + '.txt'

        path_to_master_MakeFile = Path(f"/home/user1/MasterMakeFile") #Path to MakeFile outside the test directory
        with (my_dir / file_name).open('w') as f:
            # Randomization for IDPT Scenarios
            if choice_of_random == 0:
                # 从预生成的无重复列表中取对应位置的字典
                # 若迭代次数超过字典总数,示例默认重复使用最后一个字典,可按需调整
                random_dict = random_dicts[i-1] if i-1 < len(random_dicts) else random_dicts[-1]
                
                for key, value in dict_0.items():
                    f.write(key + '\n')
                    for key1, value1 in value.items():
                        f.write(f"{key1} :={value1}\n")
                    f.write(f"{'}'}")
                    f.write(f"\n\n")
                for key, value in random_dict.items():
                    f.write(key + '\n')
                    for key1, value1 in value.items():
                        f.write(f"{key1} :={value1}\n")
                    f.write(f"{'}'}")
                    f.write(f"\n\n")
                for key_dict, value_dict in MAIN_DICT.items():
                    f.write(key_dict + '\n')
                    for key1, value1 in value_dict.items():
                        f.write(f"{key1} :={value1}\n")
                    f.write(f"{'}'}")
                    f.write(f"\n\n")
            shutil.copy("/home/user1/Makefile", my_dir)  # To copy MakeFile into the Iteration Directories
            shutil.copy("/home/user1/some_filename.cpp", my_dir)  # To copy .cpp file into the Iteration Directories
            shutil.copy("/home/user1/Makefile", path_to_master_MakeFile)


dict_0 = {
    'DICT_0 {': {
        'color': "pink;"
            }
        }

dict_1 = {
    'DICT_1 {': {
        'color': "red;"
            }
        }
dict_2 = {
    'DICT_2 {': {
        'color': "green;"
            }
        }
dict_3 = {
    'DICT_3 {': {
        'color': "blue;"
            }
        }
dict_4 = {
    'DICT_4 {': {
        'color': "orange;"
            }
        }
dict_5 = {
    'DICT_5 {': {
        'color': "violet;"
            }
        }
MAIN_DICT = {
    'MAIN_DICT {' : {
        'color': "gray;"
    }
 }

sample()

关键修改说明

  1. 预生成无重复序列:在循环开始前,使用random.sample(needed_dicts, k=sample_count)生成指定长度的无重复随机字典列表,sample_count取迭代次数和字典总数的较小值,避免索引越界。
  2. 循环中按序取值:每次循环直接从预生成的列表中按索引取字典,确保每个字典仅被使用一次(当迭代次数≤字典总数时)。
  3. 边界处理:若迭代次数超过字典总数,示例中默认重复使用最后一个字典,你可根据需求调整这部分逻辑(如抛出提示、循环序列等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:19:52