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

Random Pair Generator: How to stop people coming up multiple times?

我正在创建一个很小的 ​​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)

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