首页 > 解决方案 > 为列表中的每个项目随机分配一对而不重复

问题描述

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

例如。

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

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

标签: pythonrandom

解决方案


您可以只构建一个随机排序的项目列表,然后将它们配对为键值

一方面,您将获取列表,另一方面从 item 旋转相同的列表values[1:] + [values[0]],然后将两者压缩成 2×2 对,并从这些对中构建一个 dict

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)

推荐阅读