将N个人分成2人一组

问题描述

我编写了以下代码,将N个人分为2个随机小组,但在许多情况下,我得到了错误pop index out of range

有人可以帮我吗?

from random import seed
from random import randrange
from datetime import datetime
seed(datetime.Now())

N = int(input("How many students do you have?:"))

pupils = set()

for number in range(N):
    pupils.add(str(input('pupil name:')))
print(pupils)


teams = set()
lista = list(pupils)
for i in range(N//2):#// akerea dieresi
    pos1 = randrange(0,len(lista))
    pos2 = randrange(0,len(lista))
    pupil1 = lista.pop(pos1)
    pupil2 = lista.pop(pos2)
    team = (pupil1,pupil2)
    teams.add(team)

i = 0
for team in teams:
    i+=1
    print(team + str(i))

解决方法

编辑: 此错误意味着您正在尝试从不在列表中的索引来pop()。 每次尝试取出东西时,请尝试检查列表是否已为空。我将使用if lista来验证它是否为空。


teams = set()
lista = list(pupils)
for i in range(N//2):  #notice yo only have to do that N//2 times!
    if lista:                       #check if lista is empty
        pos1 = randrange(0,len(lista))
        pupil1 = lista.pop(pos1)
    if lista:
        pos2 = randrange(0,len(lista))
        pupil2 = lista.pop(pos2)

    team = (pupil1,pupil2)
    teams.add(team)

i = 0
for team in teams:
    i+=1
    print(team + str(i))
,

您的直接问题是您正在缩短list,但是像删除的索引一样应该仍然存在。更大的问题是您正在尝试发明自己的random.shuffle()。通过使用内置的random.shuffle(),可以大大简化您的代码。

import random

#represents the results of your name input system
names = 'Tom Jerry Abbot Costello Regis Kelly Harry Sally Thelma Louise Solomon'.split()

#shuffle all the names
random.shuffle(names)

teams = []

#keep going as long as there are pairs
while len(names) > 1:
    teams.append({names.pop(),names.pop()})

#odd man out
if names:
    print(f"{names.pop()} can't play")

#results
print(*teams,sep='\n')