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

标签 python random

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

例如。

list = ["dog", "cat", "rat", "bird", "monkey"]

我想要一个像
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}

我想要的是:
  • 值不能分配给自身,例如不是 {"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
    

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

    最佳答案

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

    一方面,您将获取列表,另一方面,从项目 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']
  • zipper 给 [('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/

    相关文章:

    python - 获取 Azure 中连接到不同订阅中的工作区的虚拟机的日志分析工作区 ID

    python - 学习 Python 之外的脚本语言

    c - 浮点异常(核心已转储)。在创建者随机数中

    javascript - 使用 Math.random() 生成均匀分布

    javascript - 如何在 jQuery/JS 中创建具有多个值的 obj 并随机选择不重复的值

    python - 如何将其中包含换行符的字符串转换为 Python 中的列表?

    python - 需要使用python从网络浏览器下载文件

    python - 重新索引分层索引数据帧的子级

    linux - 比/dev/random 更快但在密码学上有用的 RNG?

    python - 如何在numpy中的二维矩阵中随机采样