【问题标题】:Python randomly matching two arrays, e.g. Owners and GiftsPython 随机匹配两个数组,例如业主和礼物
【发布时间】:2022-01-22 08:00:51
【问题描述】:

假设我有两个数组

people = ['tom', 'dick', 'harry']
gifts = ['toms', 'dicks', 'harrys']

我想随机分配一个人给一个礼物,但我不想分配给他们自己的。

我遇到了麻烦,因为诸如 random.choice 之类的解决方案不知道不挑选一个人自己的礼物的限制。我目前的技巧是将礼物列表随机移动(1,n-1),但显然那不是随机的。

我觉得我错过了一些明显的东西?有什么常用的方法吗?

【问题讨论】:

  • 你知道列表中的位置对吗?
  • 像` {'tom': 'dicks', 'dick': 'toms'}`这样的选择也是个问题
  • 给定的列表有多大?数百?数千?一块内存都装不下?

标签: python arrays algorithm random


【解决方案1】:

这应该适合你。

import random

people = ['tom', 'dick', 'harry', 'arne']
gifts = ['toms', 'dicks', 'harrys', 'arne']

# assign each person a gift randomly but not at the
# same index and don't repeat the same gifts twice so remove them

gift_dict = {}
for people_index in range(len(people)):
    gift_choice = people_index
    while gift_choice == people_index:
        gift_choice = gifts.index(random.choice(gifts))
    gift_dict[people[people_index]] = gifts[gift_choice]
    gifts.pop(gift_choice)

print(gift_dict)

输出

{'tom': 'harrys', 'dick': 'arne', 'harry': 'dicks', 'arne': 'toms'}

【讨论】:

    【解决方案2】:

    您可以使用random.shuffle() 随机播放您的列表之一,然后您可以zip() 他们。这应该可以解决问题,而不必担心内存。

    import random
    people = ['tom', 'dick', 'harry']
    gifts = ['toms', 'dicks', 'harrys']
    random.shuffle(gifts)
    results = dict(zip(people, gifts))
    print(results)
    

    【讨论】:

      【解决方案3】:

      假设没有人收到超过一份礼物(如果可以的话,您可以查看itertools.product)。诀窍是让每个人都找到任何“有效的接收者”来申请random.choice()。主要标准似乎是你不能给自己或给你的人:

      我相信会有更有效的解决方案,但这会让你开始:

      import random
      
      givers = ['tom', 'dick', 'harry', "joe"]
      receivers  = givers.copy()
      receivers_givers = {}
      for giver in givers:
          # ---------------------
          # You can't give to yourself or to the person who gave to you.
          # ---------------------
          valid_receivers  = [reciever for reciever in receivers  if reciever not in (giver, receivers_givers.get(giver))]
          # ---------------------
      
          receiver = random.choice(valid_receivers)
          receivers.remove(receiver)
          receivers_givers[receiver] = giver
      
      for reciever, giver in receivers_givers.items():
          print(f"{giver} gifts to {reciever}")
      

      这应该会给你类似的东西:

      tom gifts to joe
      dick gifts to harry
      harry gifts to tom
      joe gifts to dick
      

      【讨论】:

        猜你喜欢
        • 2013-10-29
        • 1970-01-01
        • 2019-03-15
        • 2015-02-05
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多