gpt4 book ai didi

python - 根据另一个列表随机替换字典列表中的元素

转载 作者:行者123 更新时间:2023-12-01 01:56:53 25 4
gpt4 key购买 nike

它看起来像一个游戏,但我需要它来评估我正在研究的模型。需要一些帮助...我有一本字典,其中包含列表作为值。我只需要用 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')...]

最佳答案

如果我理解正确,你可以这样做:

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']}

关于python - 根据另一个列表随机替换字典列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com