gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:00:24 25 4
gpt4 key购买 nike

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

例如。

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com