zoukankan      html  css  js  c++  java
  • python-随机数的产生random模块

    random模块用来产生随机数:

    查看random模块的方法:

    import random
    
    random.__dir__
    Out[39]: <function __dir__>
    
    random.__dir__()  #此方法可以查看某个模块的方法

    产生随机数:

    产生0~1之间的随机数:

    random.random()   #此方法只会产生0~1之间的随机数
    Out[42]: 0.14584365038166225
    
    random.random()
    Out[43]: 0.5366296300103158
    
    random.random()
    Out[44]: 0.936239179720834
    
    random.random()
    Out[45]: 0.09407523351903868
    
    random.random()
    Out[46]: 0.4499090927149705

    产生随机整数:

    random.randint(1,3)#包含数字3
    Out[50]: 1
    
    random.randint(1,3)
    Out[51]: 1
    
    random.randint(1,3)
    Out[52]: 2
    
    random.randint(1,3)
    Out[53]: 3
    
    ############
    random.randrange(1,3) #不包含数字3
    Out[56]: 2
    
    random.randrange(1,3)

    产生随机浮点数:

    random.uniform(3,4)  #产生整形之间的浮点数
    Out[61]: 3.7472254465353703
    
    random.uniform(3.545,9.656)  #给出浮点数,产生这之间的浮点数
    Out[62]: 8.45786901292924
    
    random.uniform(13.545,9.656)  # 位置的大小可以互换
    Out[63]: 11.45893194445811

    从序列中随机选一个元素:

    序列可以为:列表,元组,字符串。

    random.choice(list("abcdef"))  #列表
    Out[66]: 'd'
    
    random.choice(list("abcdef"))
    Out[67]: 'f'
    
    random.choice(tuple("abcdef"))  #元组
    Out[68]: 'd'
    
    random.choice(tuple("abcdef"))
    Out[69]: 'b'
    
    random.choice("abcdef")  #字符串
    Out[70]: 'f'
    
    random.choice("abcdef")
    Out[71]: 'a'

    从序列中随机挑选k个元素,返回一个列表,并不改变原序列的值。

    d = list("dfgfdgjfdgergg")  #l
    random.sample(d, 3) Out[76]: ['f', 'd', 'f'] #注意返回的结果都是列表 td = tuple("dfgfdgjfdgergg") random.sample(td, 3) Out[80]: ['g', 'g', 'd']

    打乱原序列中值得顺序:没有返回结果,直接更改原序列

    lq
    Out[95]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    
    random.shuffle(lq)
    
    lq
    Out[97]: ['i', 'g', 'd', 'c', 'a', 'b', 'f', 'h', 'e', 'j']
  • 相关阅读:
    zookeeper使用场景
    zookeeper安装配置
    hadoop 远程调试
    deep learning笔记
    Sentiment Analysis(1)-Dependency Tree-based Sentiment Classification using CRFs with Hidden Variables
    PRML阅读笔记 introduction
    Python 学习笔记(2)
    python nltk 学习笔记(5) Learning to Classify Text
    python nltk 学习笔记(4) Writing Structured Programs
    python nltk 学习笔记(3) processing raw text
  • 原文地址:https://www.cnblogs.com/wxzhe/p/8933723.html
Copyright © 2011-2022 走看看