因此,我有一个列表,我想将这些值“分配”给其他随机值。
例如。
list = ["dog", "cat", "rat", "bird", "monkey"]
我想要一个类似的输出
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}
我想要的是:
- 不能为其分配值,例如{{cat“:” cat“}
- 一个值只能分配一次,例如{{cat“:” dog“,” rat“:” dog“}
- 值不能相互分配,例如{{cat}:“ dog”,“ dog”,“ cat”}
我尝试了这段代码:
def shuffle_recur(_list):
final = {}
not_done = copy.deepcopy(_list)
for value in _list:
without_list = not_done.copy()
if value in without_list :
without_list.remove(value)
if value in final.values():
for final_key, final_value in final.items():
if final_value == value:
print(final_value, ' ', final_key)
if final_key in without_list :
without_list.remove(final_key)
if len(without_list) < 1:
print('less')
return shuffle_recur(_list)
target = random.choice(without_list)
not_done.remove(target)
final[value] = target
print('{} >> {}'.format(value, target))
return final
但这非常混乱,我认为这不是最好的方法。 有什么更好的方法可以做到这一点?谢谢你的帮助。