目的
最近和朋友们想玩圣诞互换礼物,但是没找到可以抽奖的小程序,所以我决定自己写一个。
游戏规则:参加游戏的人需要随机抽取一个幸运儿送一个礼物,但是注意不要抽到自己,并且不要重复抽同一个人。
思路
准备两个列表:抽奖人员列表和被抽人员列表。
依次遍历每个抽奖人员,在剩下的被抽人员列表里随机抽取一个幸运儿。抽取后将该幸运儿从被抽人员列表中剔除,然后进行下一轮抽取。
代码
import random
participants = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] #参与抽奖的人
def lottery(participants):
"""
抽奖
:param participants: 参与抽奖的人
:return:
"""
the_rest = participants.copy() # 没被抽中的人,注意要用复制函数,不能直接赋值,不然会后续删除the_rest的元素时也会删除participants的元素
choose_one = {} # 存每个人抽中的人
num = len(participants) # 参加抽奖的人数
for i in range(num):
participant = participants[i] # 本次抽奖者
lucky_person = '' # 被抽中的人
# 从没被抽中的人(the_rest)中抽取一位幸运儿
while lucky_person == '' or lucky_person == participant: # 确保不会选到自己
lucky_person = random.choice(the_rest)
# 将本次抽奖结果存入choose_one
choose_one[participant] = lucky_person
# 将被抽中的人从没被抽中的人(the_rest)里删除
the_rest.remove(lucky_person)
return choose_one
print('送礼物的:幸运儿')
print('-------------')
result = lottery(participants)
for item in result.items():
print("{} : {}".format(item[0], item[1]))