冰丶咖啡 发表于 2020-10-29 18:09:51

【初学者求问】随机数中出现重复的值怎么去除

如题,新手!~
自己写了个随机出大乐透号的代码,但是在执行过程中同一区会出现重复的数值,请问各位大佬怎么消除这个问题。谢谢!
#!/usr/bin/env python3
import random
red = (random.randint(1,36) for i in range(5))
blue = (random.randint(1,13) for j in range(2))
print("前区:",list(red))
print("后区:",list(blue))

不能懒 发表于 2020-10-29 19:11:14

set集合或者使用if not in 语句试试看

qiuyouzhi 发表于 2020-10-29 19:12:31

这样行吗
#!/usr/bin/env python3
import random
redlst =
bluelst =
red = []
blue = []
for i in range(5):
    temp = random.choice(redlst)
    red.append(temp)
    redlst.remove(temp)
for i in range(2):
    temp = random.choice(bluelst)
    blue.append(temp)
    bluelst.remove(temp)

print("前区:", red)
print("后区:", blue)

mrcrisis 发表于 2020-10-29 19:26:09

一种是判断一下是否已经取出,另一种用sample
import random
red = random.sample(range(1,36),5)
print("前区:",list(red))

疾风怪盗 发表于 2020-10-29 19:30:45

三楼是一种思路,或者也可以按2楼说的用集合,也蛮方便的
import random
red=set()
blue=set()
while len(red)<5:
    red.add(random.randint(1,36))
while len(blue)<2:
    blue.add(random.randint(1,13))

red = (random.randint(1,36) for i in range(5))
blue = (random.randint(1,13) for j in range(2))
print("前区:",list(red))
print("后区:",list(blue))

冬雪雪冬 发表于 2020-10-29 19:34:06

#!/usr/bin/env python3
import random
red = list(range(1, 37))
random.shuffle(red)
blue = list(range(1,14))
random.shuffle(blue)
print("前区:",red[:5])
print("后区:",blue[:2])

hrp 发表于 2020-10-29 19:36:51

random.sample是最直接的,4楼有例子
页: [1]
查看完整版本: 【初学者求问】随机数中出现重复的值怎么去除