如何使用Python中的随机函数避免列表中字典的重复?

问题描述 投票:0回答:1
#!/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"))
    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:
            needed_dicts = [dict_1, dict_2, dict_3, dict_4, dict_5]

            # Randomization for IDPT Scenarios
            if choice_of_random == 0:
                random_dict = random.sample(needed_dicts, k=1)[0]
                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()

这是我的代码,它有 5 个字典(dict_1、dict_2、dict_3、dict_4、dict_5)分配给变量 need_dicts 列表。每个字典都需要写入 file_name.txt。对于每个文件,必须始终写入 dict_0 和 MAIN_DICT,但代码必须在 dict_1、dict_2、dict_3、dict_4、dict_5 中随机选择一个 dict。上面编写的代码就是这样做的,但是当我的代码提示“输入文件生成的迭代次数”并且我给出5时,那么在5个文件中,dict_1被写入2次,dict_2被写入2次,dict_3被写入1次。我希望代码随机选择这 5 个字典中的任何一个并将其写入文件而不重复,并且应该是唯一的。 例如 - 如果我将 5 作为“输入文件生成的迭代次数”的输入,文件 1 可以写入 dict_4,文件 2 可以写入 dict_3,文件 3 可以写入 dict_1,文件 4 可以写入dict_2,对于文件 5,它可以写入 dict_5。请帮我这样修改上面的代码。

python-3.x random
1个回答
0
投票

根据您的描述,这是有效的。我从你的文件中删除了一些无用的控件,因为我不需要它们

import random
import shutil
from pathlib import Path
import itertools

def sample() -> None:
    number_of_iteration = int(input("Enter the number of iterations for file generation\n"))
    needed_dicts = [dict_1, dict_2, dict_3, dict_4, dict_5]

    # Shuffle the list of other dictionaries
    random.shuffle(needed_dicts)

    # Use itertools.cycle to cycle through the shuffled dictionaries
    dictionaries_cycle = itertools.cycle(needed_dicts)

    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:
            # Always write DICT_0 first
            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")

            if i > 5:
                # After the first 5 iterations, shuffle the list of dictionaries again
                random.shuffle(needed_dicts)
                dictionaries_cycle = itertools.cycle(needed_dicts)

            # Write one of the shuffled dictionaries (or cycle through them)
            current_dict = next(dictionaries_cycle)
            for key, value in current_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")

            # Write MAIN_DICT last
            for key, value in MAIN_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")

        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()

尝试一下并告诉我:)

© www.soinside.com 2019 - 2024. All rights reserved.