它看起来像一个游戏,但我需要这个来评估我正在研究的模型。需要一些帮助...
我有一个字典列表作为值。我需要使用my_list
中的元素替换每个列表中每个列表中的一个元素,但该元素不在列表中。
然后我需要打印哪些字母最好作为元组列表显示原始字典中的每个键。
到目前为止,我的代码根据需要不起作用......:
my_list=[['a','b','c','d','e','q'],['f','j','k','l','m','n'],['o','p','r','s','t','k'], ['e','s','w','x','h','z']]
my_dict = {0:['a','d','f'], 1:['o','t','e'], 2:['m', 'j', 'k'],3:['d','z','f']}
all_letters = set(itertools.chain.from_iterable(my_list))
replace_index = np.random.randint(0,3,4)
print(replace_index)
dict_out = my_dict.copy()
replacements = []
for key, terms in enumerate(my_list):
print(key)
print(terms)
other_letters = all_words.difference(terms)
print(other_letters)
replacement = np.random.choice(list(other_letters))
print(replacement)
replacements.append((terms[replace_index[key]], replacement))
print(replacements)
dict_out[replace_index[key]] = replacement
print(dict_out)
print(replacements) # [(o,('a','c')...]
答案 0 :(得分:2)
如果我理解正确,你可以这样做:
import numpy as np
for i, k in enumerate(my_dict):
# Pick a random element of your list in each key of my_dict:
original = my_dict[k][np.random.randint(0, len(my_dict[i]))]
# Pick a random element of the corresponding list, that is not in the my_dict key
replacement = np.random.choice(list(set(my_list[i]) - set(my_dict[k])), 1)[0]
# Replace the original for the replacement
my_dict[k][my_dict[i].index(original)] = replacement
# Print what was switched
print((k,(original, replacement)))
输出结果为:
(0, ('a', 'e'))
(1, ('t', 'm'))
(2, ('m', 't'))
(3, ('f', 'h'))
您的my_dict
现在看起来像是:
{0: ['e', 'd', 'f'], 1: ['o', 'm', 'e'], 2: ['t', 'j', 'k'], 3: ['d', 'z', 'h']}