【问题标题】:Randomly replace elements in a dictionary lists based on another list根据另一个列表随机替换字典列表中的元素
【发布时间】:2018-10-08 15:11:08
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x list dictionary random


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 2021-02-19
      • 2021-07-16
      • 2021-09-18
      • 2018-08-19
      • 2021-07-20
      • 1970-01-01
      • 2022-07-10
      • 1970-01-01
      相关资源
      最近更新 更多