python,random随机数的获取

  随机数生成

  首先我们需要在程序中引入random》》》import random as r

  r.random()用于生成一个随机的浮点数,

>>> print(r.random())
           
0.23928059596578843
>>> 

  r.uniform(10,20),生成一个随机的浮点数,如果a>b 则a为上限,b为下限。如果a<b,则b为上限

>>> print(r.uniform(10,20))
           
15.995495884011348
>>> print(r.uniform(20,10))
           
13.179092381602349
>>> 
#如果没有给定a,b那么会报错

>>> print(r.uniform())

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(r.uniform())
TypeError: uniform() missing 2 required positional arguments: 'a' and 'b'
>>> print(r.randint())

  r.randint(a,b),生成一个随机的整数,a 是下限,b是上限。下限必须小于上限

>>> print(r.randint())
           
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print(r.randint())
TypeError: randint() missing 2 required positional arguments: 'a' and 'b'
>>> print(r.randint(1,10))
           
1

 >>> print(r.randint(10,1))
  Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
  print(r.randint(10,1))
  File "D:\python\lib\random.py", line 222, in randint
  return self.randrange(a, b+1)
  File "D:\python\lib\random.py", line 200, in randrange
  raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
  ValueError: empty range for randrange() (10,2, -8)
 >>>

  r.randrange(a,b,1or2),随机取出指定范围内的奇偶数,1奇数 2偶数

>>> r.randrange(0,10,2)
           
6
>>> r.randrange(0,10,1)
           
1
>>> r.randrange(0,10,1)
           
7
>>> 

  r.choice('qwertuiopolkjhgffdsa')所及取出某一个字符

>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
           
k
>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
           
n
>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
           
t
>>> 

  r.sample(str,num),会随机输出num个字符,且num一定小于等于len(str)

# 小于字符长度时
>>> r.sample('qweasd',2)
           
['d', 'q']
# 大于字符长度时
>>> r.sample('qweasd',8)
           
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    r.sample('qweasd',8)
  File "D:\python\lib\random.py", line 319, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
# 等于字符长度时
>>> r.sample('qweasd',6)
           
['s', 'd', 'a', 'e', 'w', 'q']
>>> 

  洗牌,也就是随机排序

>>> items = [1,2,3,4,5,6]
           
>>> r.shuffle(items)
           
>>> items
           
[3, 6, 1, 5, 2, 4]
>>> 

 

转载于:https://www.cnblogs.com/pengpengzhang/p/8711344.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值