随机配对生成器:如何防止人们多次出现?

3

我正在创建一个小型的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() 从每个列表中删除项目,以确保没有重复吗? - Random Davis
3
选择一个随机项目后,从列表中删除该项目,以便不能再次选择它。 - John Gordon
导师和学员名单是一对一的吗?即长度相等吗? - JL Peyret
1个回答

7
使用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)]

1
不错。如果导师/学员列表长度不相等(比如每个导师可以有2个学员),那么这个方法就行不通了,但既然没有提到这种可能性,那就加一分。 - JL Peyret

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接