马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想用python写一个随机点名的代码,我自己尝试用random.randint()来表达,但我发现使用random()来表达会一个问题,就是有时会重复,比如:
import random
num = random.randint(0,50)
print(num)
当我去运行的时候,有时会打印1,有时也会打印2,但有时又会打印1,就会出现重新的数字,我想打印十次,但每次打印出来的数字都是不同的,该怎么实现呢?
如果有哪位大佬知道,麻烦能否耽误大家几分钟的时候教我一下,鄙人万分感谢!
本帖最后由 jackz007 于 2022-10-7 21:28 编辑
这个代码会在 [1 , 50] 的范围内随机产生 50 个不重复的元素列表 import random
c , d = 0 , []
while c < 50:
x = random . randint(1 , 50)
if not x in d:
d . append(x)
c += 1
print(d)
运行实况: D:\[00.Exerciese.2022]\Python>python x.py
[16, 50, 32, 5, 40, 48, 21, 47, 19, 49, 28, 8, 25, 26, 42, 39, 31, 12, 10, 14, 35, 44, 18, 23, 7, 34, 17, 15, 33, 22, 27, 43, 46, 45, 1, 38, 2, 20, 9, 30, 6, 4, 36, 37, 3, 13, 29, 24, 41, 11]
D:\[00.Exerciese.2022]\Python>python x.py
[22, 16, 7, 15, 11, 12, 13, 9, 34, 2, 45, 32, 43, 50, 21, 17, 24, 14, 4, 47, 6,27, 19, 29, 37, 5, 33, 42, 36, 31, 49, 46, 35, 3, 38, 40, 41, 8, 26, 25, 48, 10, 28, 18, 30, 39, 44, 1, 20, 23]
D:\[00.Exerciese.2022]\Python>python x.py
[43, 37, 24, 16, 14, 1, 5, 21, 30, 49, 11, 17, 22, 7, 47, 12, 20, 18, 13, 44, 26, 48, 36, 28, 50, 10, 15, 41, 29, 6, 31, 38, 32, 42, 3, 40, 2, 8, 39, 33, 45, 34, 4, 25, 46, 19, 9, 35, 27, 23]
D:\[00.Exerciese.2022]\Python>python x.py
[49, 3, 1, 18, 28, 36, 23, 10, 38, 2, 34, 24, 30, 42, 25, 16, 12, 22, 9, 43, 11, 4, 8, 33, 27, 37, 32, 47, 39, 40, 41, 35, 6, 45, 48, 15, 21, 5, 14, 50, 17, 13, 7, 26, 20, 31, 44, 29, 46, 19]
D:\[00.Exerciese.2022]\Python>
|