Python3实现随机数
但是,有一点需要注意:Python random是伪随机数。
那么,可以借用python random实现真随机数吗?答案是No。所谓真随机数,是要求根据绝对随机事件产生的数,也就是说要求要有一个无因果关系的随机事件,那么,这玩意只存在与哲学领域……
目前的随机数产生都是统计上的随机,因为随机源都是自然事件,顶天了算是混沌变量,绝对的无因果大概是不存在的。
不过统计随机基本上都够用了吧……
还是老老实实的用random模块吧….
代码演示
import random#随机整数import stringprint(random.randint(0,99))#随机选取0到100间的偶数print(random.randrange(0, 101, 2))#随机浮点数print(random.random())print(random.uniform(1, 10))#随机字符print(random.choice('abcdefg%^*f'))#多个字符中选取特定数量的字符print(random.sample('abcdefghij',3))#多个字符中选取特定数量的字符组成新字符串# print(string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ",""))#随机选取字符串print(random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ))#洗牌items = [1, 2, 3, 4, 5, 6]random.shuffle(items)print("洗牌:", items)#从指定序列中随机获取k个元素作为一个片段返回,不会改变原有序列list = []list = random.sample(items,2)print(list)
结果
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
新闻热点
疑难解答
图片精选