Python之random模块(随机数模块)

2021-06-28 17:04

阅读:518

标签:迭代   rand   amp   choice   对象   dom   form   orm   color   

  • random.random()

    产生(0,1)范围的随机浮点数

>>> i=0
>>> while i:
    print(random.random())
    i+=1

    
0.9848013389436461
0.4012610801121991
0.9401837669813049
0.36164185591353215
0.7291907908539083
0.7861886854506668
0.36611102654772787
0.37398351354553305
0.12664074395881753
0.12236860697016771
  • ret=random.uniform(m, n)

   产生(m,n)范围的随机浮点数

>>> i=0
>>> while i:
    print(random.uniform(1,3))
    i+=1

    
1.6814043787561306
1.0907622843587292
1.009237282651322
2.2605331784482594
2.1378180187272346
1.668827901441295
2.8266941473808895
1.5744320484197392
1.432510006768112
2.8973319467167453
  • random.randint(m, n)

   产生[m, n]范围的随机整数

>>> i=0
>>> while i:
    print(random.randint(1,5),end=, )
    i+=1

    
3, 2, 4, 5, 5, 4, 5, 1, 2, 4, 
  • ret=random.randrange(m, n)

   产生[m, n)范围内的随机整数

>>> i=0
>>> while i:
    print(random.randrange(1,5),end=, )
    i+=1

    
3, 1, 3, 3, 2, 4, 3, 1, 4, 1, 
  • ret=random.choice(可迭代对象)

   传入一个可迭代对象,在该对象中随机选择一个元素

>>> i=0
>>> while i:
    print(random.choice([1,2,3,4,5]),end=, )
    i+=1

    
2, 4, 4, 2, 4, 2, 4, 3, 5, 1, 
  • random.sample(可迭代对象, n)

   传入一个可迭代对象,在该对象中随机选择n个元素

>>> i=0
>>> while i:
    a, b = random.sample([1,2,3,4,5],2)
    print((a,b),end=, )
    i+=1

    
(2, 3), (2, 4), (5, 2), (5, 3), (5, 4), (3, 2), (2, 1), (4, 5), (4, 1), (1, 4), 
  • random.shuffle(可迭代对象)

   传入一个有序可迭代对象,可打乱其元素顺序

>>> li=[1,2,3,4,5,6,7]
>>> i=0
>>> while i:
    random.shuffle(li)
    print(li)
    i+=1

    
[6, 2, 5, 4, 1, 3, 7]
[7, 6, 5, 3, 2, 1, 4]
[7, 2, 6, 1, 4, 3, 5]
[6, 5, 4, 3, 7, 1, 2]
[4, 2, 1, 5, 3, 7, 6]
[3, 2, 4, 7, 5, 1, 6]
[2, 3, 6, 4, 7, 1, 5]
[1, 5, 7, 6, 2, 3, 4]
[3, 2, 7, 6, 5, 4, 1]
[5, 7, 6, 1, 3, 4, 2]

 

Python之random模块(随机数模块)

标签:迭代   rand   amp   choice   对象   dom   form   orm   color   

原文地址:https://www.cnblogs.com/chenchaoze/p/9648593.html


评论


亲,登录后才可以留言!