所以我有一个列表,我想将这些值“分配”给不同的随机值。
例如。
list = ["dog", "cat", "rat", "bird", "monkey"]
我想要一个像
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "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
但它非常困惑,我认为这不是最好的方法。
什么是更好的方法来做到这一点?
最佳答案
您可以只构建一个随机排序的项目列表,然后将它们配对为键值
一方面,您将获取列表,另一方面,从项目 values[1:] + [values[0]]
开始旋转的相同列表,然后将两者压缩成一对 2×2 对,并从这些对构建一个字典
values = ["dog", "cat", "rat", "bird", "monkey"]
shuffle(values)
result = dict(zip(values, values[1:] + [values[0]]))
例子
['bird', 'dog', 'rat', 'monkey', 'cat']
['dog', 'rat', 'monkey', 'cat', 'bird']
[('bird', 'dog'), ('dog', 'rat'), ('rat', 'monkey'), ('monkey', 'cat'), ('cat', 'bird')]
print(values) # ['bird', 'dog', 'rat', 'monkey', 'cat']
print(result) # {'bird': 'dog', 'dog': 'rat', 'rat': 'monkey', 'monkey': 'cat', 'cat': 'bird'}
如果您不希望映射相互跟随,只需
shuffle
第二次mappings = list(zip(values, values[1:] + [values[0]]))
shuffle(mappings)
result = dict(mappings)
关于python - 为列表中的每个项目随机分配一对而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698594/