import random
#举例:
print(random.random()) #生成[0-1)之间的随机浮点数,如0.026625942802680824
print(random.randint(1,10)) #生成[1,10]之间的随机整数,如6
print(random.randrange(1,10,2)) #生成[1,10]之间间隔为2的随机整数(就是1 3 5 7 9当中随机),如5
print(random.uniform(1.1,5.4)) #生成[1.1, 5.4]之间的随机浮点数,如2.6459649937889846
print(random.choice(['a','b','c'])) #从序列中随机取一个元素,如a
print(random.sample('zyxwvutsrqponmlkjihgfedcba',5))
#对指定序列或集合set,从中选择指定数量的元素生成列表,如['m', 'f', 'p', 'o', 'c']
lists=[1,2,3,4,5,6]
random.shuffle(lists) #对指定列表打乱排序,如[3, 6, 4, 5, 2, 1]
print(lists)
举例:输出一个list,包含了10个随机不重复的4位数,每1秒生成一个
import random
import time
lists=[]
for i in range(10):
num1=random.randint(1,9)
while True:
num2 = random.randint(0, 9)
if num2==num1:
continue
else:
break
while True:
num3 = random.randint(0, 9)
if num3==num1 or num3==num2:
continue
else:
break
while True:
num4 = random.randint(0, 9)
if num4==num1 or num4==num2 or num4==num3:
continue
else:
break
#print('num1=',num1,'num2=',num2,'num3=',num3,'num4=',num4)
totalnum=int(str(num1)+str(num2)+str(num3)+str(num4))
time.sleep(1)
print(totalnum)
lists.append(totalnum)
print(lists)
结果:
2605
7493
3897
6403
3179
8542
5109
2063
2903
9764
[2605, 7493, 3897, 6403, 3179, 8542, 5109, 2063, 2903, 9764]
网友评论