首页 > 解决方案 > 将 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))

标签: pythonfunctionindexoutofrangeexception

解决方案


编辑:此错误表示您正在尝试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))

推荐阅读