【问题标题】:Random Pair Generator: How to stop people coming up multiple times?随机对生成器:如何阻止人们多次出现?
【发布时间】:2021-01-09 21:28:50
【问题描述】:

我正在创建一个很小的 ​​Python 程序,它需要为我正在组织的一些小组工作生成随机对。我需要确保人和对不会出现两次。

这是我到目前为止所写的。我感觉很接近,但不知道如何解决它。

我从两个 .txt 文件中获得了两个我需要配对的人员列表,它们是随机生成的,没有问题。但是我在输出中得到了重复。

我目前正在创建列表并检查它们是否在该列表中,但有没有更简单的方法?

import random

def split_file(file_name):
  text = open(file_name)
  line = text.read()
  result = line.split("\n")
  return result

mentors = split_file(file_name="mentors.txt")
mentees = split_file(file_name="mentees.txt")

def randomiser(group):
  random_member = random.choice(group)
  return random_member

pairings = []
mentees_list = []
mentors_list = []

for i in range(20):
  mentee = randomiser(mentees)
  if mentee not in mentees_list:
     mentees_list.append(mentee)
  mentor = randomiser(mentors)
  if mentor not in mentors_list:
    mentees_list.append(mentee)
  pair = mentee + ", " + mentor
  if pair not in pairings:
      pairings.append(pair)
      print(pair)

【问题讨论】:

  • 您是否尝试过对两个列表进行洗牌,然后使用pop() 从每个列表中删除项目,从而确保没有重复?
  • 随机选择一个项目后,将该项目从列表中删除,使其无法再次选择。
  • 导师-被指导者名单是一对一的吗?即等长?

标签: python random duplicates generator


【解决方案1】:

使用random.shufflezip可以快速随机配对两个列表:

import random

mentors = ['a', 'b', 'c', 'd', 'e']
mentees = [1, 2, 3, 4, 5]

random.shuffle(mentors)
random.shuffle(mentees)

pairs = [*zip(mentors, mentees)]

输出:

[('b', 5), ('c', 1), ('a', 2), ('d', 4), ('e', 3)]

【讨论】:

  • 不错。如果导师/学员名单长度不等(例如,如果每个导师可以有 2 名学员),则不会起作用,但由于没有提到这种可能性,+1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
相关资源
最近更新 更多