如何在python中使用random函数避免列表中的字典重复?

bweufnob  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(115)
#!/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)分配给变量needed_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。请帮我修改一下上面的代码。

eqqqjvef

eqqqjvef1#

根据你的描述,这是可行的。我从你的文件中删除了一些无用的控件,因为我不需要它们。
我把字典元素放在一个列表中,每隔5次进行 Shuffle ,

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"))
    choice_of_random = int(input("Enter 0 to run A Scenarios and 1 to run B Scenarios\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'

        # Randomization for IDPT Scenarios
        if choice_of_random == 0:
            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()

试试看,让我知道:)
编辑:我添加了choice_of_random choice

相关问题