所以我有一个列表,我想将这些值“分配”给不同的随机值。
例如。
list = ["dog", "cat", "rat", "bird", "monkey"]
Run Code Online (Sandbox Code Playgroud)
我想要一个像
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
我试过这个代码:
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
Run Code Online (Sandbox Code Playgroud)
但它非常混乱,我认为这不是最好的方法。什么是更好的方法来做到这一点?
您可以使用以下内容:
ll = ["dog", "cat", "rat", "bird", "monkey"]
res = list(zip(ll, ll[1:] + ll[:1]))
print(dict(res))
# {'dog': 'cat', 'cat': 'rat', 'rat': 'bird', 'bird': 'monkey', 'monkey': 'dog'}
Run Code Online (Sandbox Code Playgroud)
zip函数可用于提取列表上的对,切片可用于连续将当前元素与下一个元素配对,以实现有效配对。