zoukankan      html  css  js  c++  java
  • Python从题目中学习:random() module

    最近在给公司培训Python,布置了一道题:

    -------------------------------------------------------------------------------------------

    Generate 10 random floats(value range is (-2.0,2.0) and precision is 1) and save as list;

    Such as: [-0.7, 0.8, 1.6, 0.1, 0.3, -1.0, 0.4, 1.0, 0.5, 0.7] ;

    -------------------------------------------------------------------------------------------

    因为用到了random模块,在此做一个总结:

    random()

    类似于uniform(),只不过下限恒等于0.0,上限恒等于1.0

    randint()

    两个整型参数,返回二者之间的随机整型

    randrange()

    它接受和range()函数一样的参数,随机返回range([start,]stop[,step])结果的一项

    uniform()

    几乎和randint()一样,不过他返回的是二者之间的一个浮点型(不包括范围上限)

    sample(seq,k)

    从指定序列中随机获取指定长度的片断

    choice()

    随机返回给定序列的一个元素

    shuffle()

    用于将一个列表中的元素打乱

    random模块用于生成随机数,下面列举几个常用的函数。

    ①random.random

    | random(...)
    | random() -> x in the interval [0, 1).

    random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0

    >>> random.random()
    0.7361643505007011

    ②random.uniform

    | uniform(self, a, b)
    | Get a random number in the range [a, b) or [a, b] depending on rounding.

    random.uniform(a, b),用于生成一个指定范围内的随机符点数。

    如果 a>b,则生成的随机数n在[a,b]之间: a <= n <= b;

    如果 a<b,则生成的随机数n在[a,b]之间: b <= n <= a。

    >>> random.uniform(10,20)
    18.084480262346535
    >>> random.uniform(20,10)
    12.289824189134892

    ③random.choice

    | choice(self, seq)
    | Choose a random element from a non-empty sequence.

    random.choice(self, seq)会从序列中获取一个随机元素。

    参数seq表示一个有序类型。字符串,list,tutple都属于sequence。

    >>> random.choice("PythonRandomModule")#字符串
    'P'
    >>> random.choice(["Delon","is","a","nice","boy"])#列表
    'a'
    >>> random.choice(("Tuple1","Tuple2","Tuple3"))#元组
    'Tuple1'

    ④random.randint

    | randint(self, a, b)
    | Return random integer in range [a, b], including both end points.

    random.randint(a, b),用于生成一个指定范围内的整数。生成的随机数n在[a,b]之间: a <= n <= b。(结束点b必须大于起始点a。)

    >>> random.randint(2,10)#随机数在[2,10]之间
    8
    >>> random.randint(10,10)#结果永远是10
    10
    >>> random.randint(10,2)#语法错误
    raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
    ValueError: empty range for randrange() (10,3, -7)

    ⑤random.randrange

    | randrange(self, start, stop=None, step=1, _int=<type 'int'>, _maxwidth=9007199254740992L)
    | Choose a random item from range(start, stop[, step]).

    | This fixes the problem with randint() which includes the
    | endpoint; in Python this is usually not what you want.

    random.randrange([start], stop[, step]) 在指定范围内,获取一个随机数从 指定的step生成的递增集合中。

    比如random.randrange(10,100,2),就相当于从[10,12,14,16,18,.....,94,96,98]的序列中获取一个随机数。

    random.randrange(10,100,2)与random.choice(range(10,100,2))一样。

    >>> random.randrange(10,100,2)
    48
    >>> random.choice(range(10,100,2))
    18

    ⑥random.sample

    | sample(self, population, k)
    | Chooses k unique random elements from a population sequence.

    | Returns a new list containing elements from the population while
    | leaving the original population unchanged. The resulting list is
    | in selection order so that all sub-slices will also be valid random
    | samples. This allows raffle winners (the sample) to be partitioned
    | into grand prize and second place winners (the subslices).

    | Members of the population need not be hashable or unique. If the
    | population contains repeats, then each occurrence is a possible
    | selection in the sample.

    | To choose a sample in a range of integers, use xrange as an argument.
    | This is especially fast and space efficient for sampling from a
    | large population: sample(xrange(10000000), 60)
    |

    random.sample(sequence, k),从指定序列中随机获取指定长度的片断。

    >>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> slice = random.sample(list,5)
    >>> slice
    [6, 5, 10, 9, 2]
    >>> list#原序列不会因为sample而改变
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    ⑦random.shuffle

    | shuffle(self, x, random=None)
    | x, random=random.random -> shuffle list x in place; return None.
    |
    | Optional arg random is a 0-argument function returning a random
    | float in [0.0, 1.0); by default, the standard random.random.
    random.shuffle(x[, random]),用于将一个列表中的元素打乱。

    >>> list = ["Python","is","powerful","languange"]
    >>> random.shuffle(list) #打乱
    >>> list
    ['powerful', 'is', 'languange', 'Python']

     -----------------------------------------------------------------------------------------

     接下来举几个例子:

    例子1:(参考http://www.cnblogs.com/yd1227/archive/2011/03/18/1988015.html):

    #随机生成[0,99]的整数:
    >>> import random
    >>> random.randint(0,99)
    21
    
    #随机选取0到100间的偶数:
    >>> random.randrange(0, 101, 2)
    42
    
    #随机浮点数:
    >>> random.random() 
    0.85415370477785668
    >>> random.uniform(1, 10)
    5.4221167969800881
    
    #随机字符:
    >>> import random
    >>> random.choice('abcdefg&#%^*f')
    'd'
    
    #多个字符中选取特定数量的字符:
    >>> random.sample('abcdefghij',3) 
    ['a', 'd', 'b']
    
    #多个字符中选取特定数量的字符组成新字符串:
    >>> import string
    >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","")
    'fih'
    
    #随机选取字符串:
    >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
    'lemon'
    
    #洗牌:
    >>> import random
    >>> items = [1, 2, 3, 4, 5, 6]
    >>> random.shuffle(items)
    >>> items
    [3, 2, 5, 6, 4, 1]

    例子2:(参考http://blog.csdn.net/xiaocaiju/article/details/6973175):

    import random  
    result = random.random()  
    print result    #生成0-1的随机数
    0.6595765656210394
      
    print random.uniform(10,12)      #10-12的随机数 
    10.806990108392618             
      
    print random.randint(30,50)  #30-50的随机整数
    50
      
    print random.randrange(10,100,2)     #从10开始到100结束,步长为2的序列中,随机选一个  
    22
    
    list = [1,2,5,6,7,8,8]  
    print random.choice(list)         #从序列中随机选一个  
    5
     
    random.shuffle(list)     #重新排列序列  
    print list  
    [5, 2, 1, 6, 8, 8, 7]
      
    list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]     
    slice = random.sample(list, 5)   #从序列中取样  
    print slice   
    [7, 3, 2, 5, 10]

    现在回到文章开头的问题,代码如下:

    """
    Generate 10 random floats(value range is (-2.0,2.0) and precision is 1) and save as list;
    
    Such as: [-0.7, 0.8, 1.6, 0.1, 0.3, -1.0, 0.4, 1.0, 0.5, 0.7] ;
    
    """
    >>> [round(random.uniform(-2,2),1) for i in range(10)]
    #[-1.0, -1.0, -1.7, 1.0, -1.1, 1.9, 1.7, 0.2, -0.9, 1.1]
  • 相关阅读:
    jsp+servlet实现的验证登陆
    Servlet转发
    ServletContext的使用
    Servlet获取配置信息(ServletConfig)
    Servlet线程安全问题(转载)
    编程式导航
    声明式导航
    Vue Router
    路由
    vue-cli 单文件组件 工具安装
  • 原文地址:https://www.cnblogs.com/dzblog/p/3924813.html
Copyright © 2011-2022 走看看