• python-随机操作(random)


    random模块作用是返回随机数,只要跟随机元素相关的,都可以使用它。

    Python标准库中的random函数,可以生成随机浮点数、整数字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等。

    1、random模块方法说明

    random.random()函数是这个模块中最常用的方法了,它会生成一个随机的浮点数,范围是在0.0~1.0之间。

    random.uniform(a,b)正好弥补了上面函数的不足,它可以设定浮点数的范围,一个是上限,一个是下限。

    random.randint(a,b)随机生一个整数int类型,可以指定这个整数的范围,同样有上限和下限值(下限必须不大于上限)。

    random.randrange([start], stop[, step])从指定范围内,按指定基数递增的集合(即等差数列)中获取一个随机数。与 random.choice(range([start], stop[, step]) 等效

    random.choice(seq)可以从任何序列,比如list列表中,选取一个随机的元素返回,可以用于字符串、列表、元组等(不能用于元组,字典)。

    random.shuffle(list)随机打乱列表元素,改变原列表。

    random.sample(seq,k)从指定的序列seq中,随机选取k个元素,不改变原序列,可以用于元组、字典。注意:输出结果为列表(list)。seq为字典时,选取的是key。

    2、实例

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2017/12/26 10:32
    # @Author  : Andes
    # @Site    :
    import random
    
    print random.random()  # 生成(0.0, 1.0)的随机数
    print random.uniform(0, 100)  # 生成随机浮点数 0<N<100
    print random.randint(0, 100)  # 生成随机整数 0<N<100
    print random.randrange(0, 100, 3)  # 随机生成一个1-100内3的倍数
    print '******************************'
    list1 = [1, 'a', 3.5, 'python', 'ha ha']
    tuple1 = (1, 2.3, 5, 6, 7.0)
    str1 = 'I am a Chinese!'
    dict1 = {'a': 1, 'b': 2.0, '25': 50, 'd': 5.5, '12': 'he he'}
    set1 = {1, 'a', 2, 'b', 3}
    print random.choice(list1), list1 # 随机选择一个列表元素
    print random.choice(tuple1), tuple1  # 随机选择一个元组元素
    print random.choice(str1), str1  # 随机选择一个字符串元素
    print '******************************'
    a = random.sample(list1, 3)
    print a, type(a), list1
    
    b = random.sample(tuple1, 3)
    print b, type(b), tuple1
    
    c = random.sample(str1, 3)
    print c, type(c), str1
    
    d = random.sample(dict1, 3)
    print d, type(d), dict1
    
    e = random.sample(set1, 3)
    print e, type(e), set1
    print '******************************'
    random.shuffle(list1)
    print list1
    
    输出结果:
    0.0920955322102
    70.2123410421
    36
    18
    ******************************
    ha ha [1, 'a', 3.5, 'python', 'ha ha']
    7.0 (1, 2.3, 5, 6, 7.0)
    I I am a Chinese!
    ******************************
    ['a', 'ha ha', 3.5] <type 'list'> [1, 'a', 3.5, 'python', 'ha ha']
    [7.0, 5, 2.3] <type 'list'> (1, 2.3, 5, 6, 7.0)
    ['e', 'h', ' '] <type 'list'> I am a Chinese!
    ['a', 'b', '25'] <type 'list'> {'a': 1, '25': 50, '12': 'he he', 'b': 2.0, 'd': 5.5}
    ['b', 1, 'a'] <type 'list'> set(['a', 1, 2, 'b', 3])
    ******************************
    [3.5, 'python', 'a', 'ha ha', 1]
  • 相关阅读:
    wpf之ComboBox绑定
    初始WPF
    WinForm 中 comboBox控件之数据绑定
    C# 操作注册表
    VS创建Web项目的两种形式WebSite和WebApplicationd的区别!
    网页加载慢的问题及部分解决办法
    获取CPU序列号
    53种使网页增速的方法、工具和资源
    Server Application Error报错解决方案
    20个使Web开发更高效的工具列表
  • 原文地址:https://www.cnblogs.com/qjoanven/p/8116778.html
Copyright © 2020-2023  润新知