This article has made two very simple codes to show that using different ideas can achieve the same effect, but the execution efficiency and code readability are quite different.
Require:
A company has 300 employees, and the annual meeting requires a lottery. The awards are as follows:
First prize: 3
second prizes: 6
third prizes: 30
winners. Last prize draw. Each employee can only win the prize once and cannot repeat it.
Code one:
import random
person = 300
alllist = []
for i in range(1,person + 1) :
alllist.append('per'+str(i))
jiang = ['三等奖','二等奖','一等奖']
no = 0
for i in [30,6,3] :
print(f'正在抽取{jiang[no]}。')
for b in range(i) :
while True :
num = 'per' + str(random.randrange(person)) # 随机生成中奖员工编号
if num in alllist : #如果随机生成的员工未被删除
break
else :
continue
print(f'第{b+1}名{jiang[no]}是{num}')
alllist.remove(num) # 删除已经中奖的员工
no += 1
code two
import random
person = 300
alllist = []
for i in range(1,person + 1) :
alllist.append('per'+str(i))
jiang = ['三等奖','二等奖','一等奖']
getpernum = [30,6,3]
no = 0
for i in getpernum :
getper = random.sample(alllist, i) #直接生成i个中奖员工的列表
print(f'获得{jiang[no]}的有:',getper)
for num in getper :
alllist.remove(num) #循环删除已经中奖的员工
print(f'还剩下{len(alllist)}人') #此句为调试用。
person -= getpernum[no]
no += 1
The advantage of code 2 is: use the sample() method of the random module to directly generate a list of winning employees in batches without generating the winning employees one by one, which improves the readability and efficiency of the code.