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

时间:2020-09-23 16:07:22

标签: python random duplicates generator

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

1 个答案:

答案 0 :(得分: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)]