我正在编写一个程序,为我正在组织的办公室清道夫狩猎随机生成组,所以我快速编写了这个简单的代码来模拟从帽子中挑选名称,但只是更公平,但不完全确定为什么它不是'工作,它没有返回所有的名称,例如我已经在列表中输入了6个名称,但它只返回其中的4个:
Group 1 consists of;
Chris
Ryan
Paul
Group 2 consists of;
Alex
我没有太多从列表中删除元素的经验,所以很可能只是我做错了。任何见解都会有所帮助。
import random
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
group=1
membersInGroup=3
for participant in participants:
if membersInGroup==3:
print("Group {} consists of;".format(group))
membersInGroup=0
group+=1
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))
答案 0 :(得分:2)
虽然pylangs' answer就足够了,但这是另一种解决问题的方法:
import random
members = 3
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
random.shuffle(participants)
for i in range(len(participants) // members + 1):
print('Group {} consists of:'.format(i + 1))
group = participants[i*members:i*members + members]
for participant in group:
print(participant)
答案 1 :(得分:1)
这个问题正在发生,因为您在迭代它时正在改变列表。解决这个问题有几种选择。一个只需要对现有代码和思维过程进行少量修改的选项就是改变列表的副本,例如participants[:]
制作副本。
使用您的代码:
import random
participants=["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul"]
group=1
membersInGroup=3
for participant in participants[:]: # only modification
if membersInGroup==3:
print("Group {} consists of;".format(group))
membersInGroup=0
group+=1
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))
示例输出:
Group 1 consists of;
Alex
Paul
Chris
Group 2 consists of;
Kimani
Elsie
Elise
Group 3 consists of;
Ryan
答案 2 :(得分:0)
这取决于列表的类型。代码有问题在行
for participant in participants:
改为使用
for participant in participants[:]: