python随机数模块的相关代码示例详解




python随机数模块

如果你对计算机语言python很了解的话,那么你对python中随机数模块是否了解呢?如果你对python随机数模块不是很了解的话,你可以浏览以下的文章对其进行了解,希望你会有所收获。

随机整数:

  1. >>> import random  
  2. >>> random.randint(0,99)  
  3. 21 

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

  1. >>> import random  
  2. >>> random.randrange(0, 101, 2)  
  3. 42 

随机浮点数:

  1. >>> import random  
  2. >>> random.random()   
  3. 0.85415370477785668  
  4. >>> random.uniform(1, 10)  
  5. 5.4221167969800881 

随机字符:

  1. >>> import random  
  2. >>> random.choice('abcdefg&#%^*f')  
  3. 'd' 

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

  1. >>> import random  
  2. random.sample('abcdefghij',3)   
  3. ['a', 'd', 'b'] 

多个字符中选取特定数量的字符组成新字符串:

  1. >>> import random  
  2. >>> import string  
  3. >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r  
  4. eplace(" ","")  
  5. 'fih' 

随机选取字符串:

  1. >>> import random  
  2. >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )  
  3. 'lemon' 

洗牌:

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


python随机数模块的相关应用以及代码的介绍。

评论关闭