提问人:Sneha Pawar 提问时间:10/17/2023 更新时间:10/18/2023 访问量:45
如何在python中使用随机函数避免列表中字典的重复?
How to avoid repetition of dictionary in a list using random function in 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"))
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中随机选择一个字典。上面写的代码是这样做的,但是当我编码提示“输入文件生成的迭代次数”时,我给出了 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。请帮我以这种方式修改上面的代码。
答:
1赞
Zackbord
10/17/2023
#1
根据您的描述,这是有效的。我从您的文件中删除了一些无用的控件,因为我不需要它们。
我将字典元素放在一个列表中,每 5 次随机播放并迭代它
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选择
评论
0赞
Sneha Pawar
10/18/2023
谢谢你的帮助,伙计!使用您的代码,我在第 36 行的赋值错误之前面临 current_dict',因此我进行了以下修改(在下一条评论中)
0赞
Sneha Pawar
10/18/2023
if choice_of_random == 0: if i <= 5: #when i<5 I was only getting MAIN_DICT & DICT_0 being written in the file and any other dict from dict_1 to dict_5 wasnt getting written # 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 current_dict = next(dictionaries_cycle) for key, value in current_dict.items():
0赞
Sneha Pawar
10/18/2023
f.write(key + '\n') for key1, value1 in value.items(): f.write(f"{key1} :={value1}\n") f.write(f"{'}'}") f.write(f"\n\n")
0赞
Sneha Pawar
10/18/2023
通过上述更改,我无法将所有 5 个字典写入 5 个文件中的每一个。我只是运行了代码并给出了迭代次数为 5,在第 1 个文件中我得到了 dict_1 在第二个文件中我得到了 dict_2,dict_4在第 3 个文件中,再次在第 4 个文件中dict_1,在第 5 个文件中再次dict_1,我不想要这种重复,无论以任何顺序随机地将这些字典写入文件,但不应该有这种重复是我期待伴侣。如果你能帮忙,那将非常有帮助.&我还需要那个choice_of_random变量bcz,我还有其他一些运行choice_of_random==1
0赞
Zackbord
10/18/2023
我更改了代码以添加 choice_of_random 变量,您可以运行它并让我知道错误是什么吗?
评论