为列表中的每个项目随机分配一对而不重复

Mad*_*n47 6 python random

所以我有一个列表,我想将这些值“分配”给不同的随机值。

例如。

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)

我想要的是:

  • 值不能分配给自身,例如 not {"cat": "cat"}
  • 一个值只能赋值一次,例如 not {"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
Run Code Online (Sandbox Code Playgroud)

但它非常混乱,我认为这不是最好的方法。什么是更好的方法来做到这一点?

Dav*_*d S 0

您可以使用以下内容:

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函数可用于提取列表上的对,切片可用于连续将当前元素与下一个元素配对,以实现有效配对。

  • 没有解释的答案毫无价值 (2认同)