双色球前6个随机数不应该重复啊,现在用randint会出现重复
来源:4-2 实操实现:随机生成双色球
风车的国度
2020-03-07 15:03:48
双色球前6个随机数不应该重复啊,现在用randint会出现重复
2回答
同学,你好。在生成随机数时,出现随机数相同的情况的机率是比较小的,鉴于同学还在python基础阶段,之后python知识积累的多了,可以将该程序完善去掉重复的情况。
同学可以参考下述代码去掉红球重复的情况
import random
for j in range(0, 6):
list1 = []
i = 0
while i < 6:
red = random.randint(1, 33)
# 判断生成的red在不在list1列表中
# 在则执行下一次循环,不在则添加到列表中
if red not in list1:
list1.append(red)
i += 1
else:
continue
blue = random.randint(1, 16)
print("红球:{}; 蓝球:{}".format(list1, blue))如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~
此团子非彼团子
2020-03-07
import random # 存在重复可能性的代码 def rand_ints_dup(a, b, k): return [random.randint(a, b) for i in range(k)] # 去除重复可能性的代码 def rand_ints_nodup(a, b, k): ns = [] while len(ns) < k: n = random.randint(a, b) if not n in ns: ns.append(n) return ns
相似问题