设为首页 加入收藏

TOP

Python random生成随机数示例
2019-03-21 22:08:01 】 浏览:81
Tags:Python random 生成 随机 示例

python生成随机数


随机整数:


>>> import random
>>> random.randint(0,99)
50


Python random生成随机数示例


随机选取0到100间的偶数:


>>> import random
>>> random.randrange(0, 101, 2)
2


Python random生成随机数示例


随机浮点数: 


>>> import random
>>> random.random()
0.011508602165174242 #范围0-1.0
>>> random.uniform(1, 10)
2.8229556607576147
>>>


Python random生成随机数示例


选择一个随机元素


>>> random.choice("abcde")
'b'
>>> random.choice("abcde")
'a'


Python random生成随机数示例


将一个列表中的元素打乱


Python random生成随机数示例


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


>>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a=random.sample(list,4)
>>> a
[6, 1, 7, 9]
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Python random生成随机数示例


随机字符:


Python random生成随机数示例


多个字符中选取特定数量的字符:


>>> import random
>>> random.sample('linuxidcabcdefgohij',3)
['o', 'u', 'l']


Python random生成随机数示例


随机选取字符串:


Python random生成随机数示例


洗牌:


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


Python random生成随机数示例


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python Numpy绘制分段函数示例 下一篇PHP删除当前目录及其目录下的所有..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目