我想把人随机分成一组。我使用了现有脚本中的以下代码,但我想添加一个条件,其中"Kimani“始终是组中的第2位
'''
import random
participants=
["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul","Chris1","Pau2l",
"Chris3","Paul3"]
group=1
membersInGroup=5
for participant in participants[:]: # only modification
if membersInGroup==5:
print("Group {} consists of;".format(group))
membersInGroup=0
group+=1
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))
'''发布于 2022-06-08 13:00:34
你可以这样做:
import math
Kimani_group = math.ceil(random.randint(1,len(participants)) / 5) # round up to the nearest random selection of a group
participants.remove(str("Kimani")) # remove Kimani as their group has already been selected, just need to insert them
for count in range(len(participants) + 1): # add +1 to participants as Kimani was part of the count but removed; changed count to the index of the loop
if membersInGroup==5:
print("Group {} consists of;".format(group))
membersInGroup=0
group+=1
if count % 5 == 1 and math.ceil((count + 1) / 5) == Kimani_group: # check if the second position in the group and that the group is the preselected group
print("Kimani")
membersInGroup+=1
continue # skip the rest of the code in this iteration and continue to the next iteration
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))这使得基马尼成为他们加入的第二组。
https://stackoverflow.com/questions/72545740
复制相似问题