Python学习笔记 - 模块 - random 随机模块

简介

random 随机模块,用于生成随机数、随机字符等.

帮助文档请点击链接:http://docs.python.org/library/random

使用方法

1
import random # 引入模块

简单使用

1
2
import random
ramdom.random()

类使用

1
2
from random import Random
r = Random()

常用函数

  • random.random()
  • random.randint(a, b)
  • random.randrange(start, stop=None, step=1)
  • random.choice(seq)
  • random.sample(population, k)
  • random.uniform(a, b)

random.choice(seq)

choice 方法接收一个参数 seq,此参数应该为一个序列(sequence)。此方法会随机返回这个序列中的一个元素

random.randint(a, b)

接收两个整数参数 ab,随机返回一个在区间 [a, b] 中的整数

random.random()

不接收任何参数,随机返回一个在区间 [0, 1) 中的数字

random.randrange(start, stop=None, step=1)

接收三个整数参数 startstopstep,通常应该是传入两个参数。

在只传入 start 参数时,会随机返回一个在区间 [0, start) 中的整数(即 start 的值只能为大于 1 的正数);
在只传入 startstop 参数时会返随机回一个在区间 [start, stop) 中的整数;
在同时传入三个参数时候,将会随机返回一个整数集合中的整数,此集合中的元素在区间 [start, stop) 中且相邻的两个元素差值为 step

注意,这个通常并不是所需要的,一般使用 random.randint

random.sample(population, k)

接收两个参数,第一个参数 population 应为一个序列,而第二个参数 k 应为一个整数。此方法会随机在序列中挑选 k 个元素并构造成 list 返回。

random.uniform(a, b)

接收两个数字参数 ab,随机返回一个在区间 [a, b) 或 [a, b] 中的数字。

注意:由于浮点数的不确定性,右端点是否包含由 a + (b-a) * random.random() 是否处于浮点数可以完美表达的点上确定,可以简单的认为很可能不包含。通常,这一点并没有影响。

不常用函数

betavariate(self, alpha, beta) method of Random instance

Beta distribution.

Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.

expovariate(self, lambd) method of Random instance

Exponential distribution.

lambd is 1.0 divided by the desired mean.  It should be
nonzero.  (The parameter would be called "lambda", but that is
a reserved word in Python.)  Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.

gammavariate(self, alpha, beta) method of Random instance

Gamma distribution.  Not the gamma function!

Conditions on the parameters are alpha > 0 and beta > 0.

gauss(self, mu, sigma) method of Random instance

Gaussian distribution.

mu is the mean, and sigma is the standard deviation.  This is
slightly faster than the normalvariate() function.

Not thread-safe without a lock around calls.

getrandbits(…)

getrandbits(k) -> x.  Generates a long int with k random bits.

getstate(self) method of Random instance

Return internal state; can be passed to setstate() later.

jumpahead(…)

jumpahead(int) -> None.  Create new state from existing state and integer.

lognormvariate(self, mu, sigma) method of Random instance

Log normal distribution.

If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.

normalvariate(self, mu, sigma) method of Random instance

Normal distribution.

mu is the mean, and sigma is the standard deviation.

paretovariate(self, alpha) method of Random instance

Pareto distribution.  alpha is the shape parameter.

seed(self, a=None) method of Random instance

Initialize internal state from hashable object.

None or no argument seeds from current time or from an operating
system specific randomness source if available.

If a is not None or an int or long, hash(a) is used instead.

setstate(self, state) method of Random instance

Restore internal state from object returned by getstate().

random.shuffle(x, random=None)

此方法接收两个参数,第一个参数为列表 x,第二个参数为一个函数 random

调用此方法后,将执行 random 所传入的函数来将列表 x 打乱顺序。

可选参数 ramdom 应该是一个不接收参数且返回一个在区间 [0.0, 1.0) 之间的数字的函数,如果留空则使用默认的 random.random() 方法。

triangular(self, low=0.0, high=1.0, mode=None) method of Random instance

Triangular distribution.

Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.

http://en.wikipedia.org/wiki/Triangular_distribution

vonmisesvariate(self, mu, kappa) method of Random instance

Circular data distribution.

mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero.  If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.

weibullvariate(self, alpha, beta) method of Random instance

Weibull distribution.

alpha is the scale parameter and beta is the shape parameter.

类使用

CLASSES
_random.Random(builtin.object)
Random
SystemRandom
WichmannHill

class Random(_random.Random)
 |  Random number generator base class used by bound module functions.
 |  
 |  Used to instantiate instances of Random to get generators that don't
 |  share state.  Especially useful for multi-threaded programs, creating
 |  a different instance of Random for each thread, and using the jumpahead()
 |  method to ensure that the generated sequences seen by each thread don't
 |  overlap.
 |  
 |  Class Random can also be subclassed if you want to use a different basic
 |  generator of your own devising: in that case, override the following
 |  methods: random(), seed(), getstate(), setstate() and jumpahead().
 |  Optionally, implement a getrandbits() method so that randrange() can cover
 |  arbitrarily large ranges.
 |  
 |  Method resolution order:
 |      Random
 |      _random.Random
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __getstate__(self)
 |  
 |  __init__(self, x=None)
 |      Initialize an instance.
 |      
 |      Optional argument x controls seeding, as for Random.seed().
 |  
 |  __reduce__(self)
 |  
 |  __setstate__(self, state)
 |  
 |  betavariate(self, alpha, beta)
 |      Beta distribution.
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |      Returned values range between 0 and 1.
 |  
 |  choice(self, seq)
 |      Choose a random element from a non-empty sequence.
 |  
 |  expovariate(self, lambd)
 |      Exponential distribution.
 |      
 |      lambd is 1.0 divided by the desired mean.  It should be
 |      nonzero.  (The parameter would be called "lambda", but that is
 |      a reserved word in Python.)  Returned values range from 0 to
 |      positive infinity if lambd is positive, and from negative
 |      infinity to 0 if lambd is negative.
 |  
 |  gammavariate(self, alpha, beta)
 |      Gamma distribution.  Not the gamma function!
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |  
 |  gauss(self, mu, sigma)
 |      Gaussian distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.  This is
 |      slightly faster than the normalvariate() function.
 |      
 |      Not thread-safe without a lock around calls.
 |  
 |  getstate(self)
 |      Return internal state; can be passed to setstate() later.
 |  
 |  lognormvariate(self, mu, sigma)
 |      Log normal distribution.
 |      
 |      If you take the natural logarithm of this distribution, you'll get a
 |      normal distribution with mean mu and standard deviation sigma.
 |      mu can have any value, and sigma must be greater than zero.
 |  
 |  normalvariate(self, mu, sigma)
 |      Normal distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.
 |  
 |  paretovariate(self, alpha)
 |      Pareto distribution.  alpha is the shape parameter.
 |  
 |  randint(self, a, b)
 |      Return random integer in range [a, b], including both end points.
 |  
 |  randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, 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.
 |      Do not supply the 'int', 'default', and 'maxwidth' arguments.
 |  
 |  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)
 |  
 |  seed(self, a=None)
 |      Initialize internal state from hashable object.
 |      
 |      None or no argument seeds from current time or from an operating
 |      system specific randomness source if available.
 |      
 |      If a is not None or an int or long, hash(a) is used instead.
 |  
 |  setstate(self, state)
 |      Restore internal state from object returned by getstate().
 |  
 |  shuffle(self, x, random=None, int=<type 'int'>)
 |      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.
 |  
 |  triangular(self, low=0.0, high=1.0, mode=None)
 |      Triangular distribution.
 |      
 |      Continuous distribution bounded by given lower and upper limits,
 |      and having a given mode value in-between.
 |      
 |      http://en.wikipedia.org/wiki/Triangular_distribution
 |  
 |  uniform(self, a, b)
 |      Get a random number in the range [a, b) or [a, b] depending on rounding.
 |  
 |  vonmisesvariate(self, mu, kappa)
 |      Circular data distribution.
 |      
 |      mu is the mean angle, expressed in radians between 0 and 2*pi, and
 |      kappa is the concentration parameter, which must be greater than or
 |      equal to zero.  If kappa is equal to zero, this distribution reduces
 |      to a uniform random angle over the range 0 to 2*pi.
 |  
 |  weibullvariate(self, alpha, beta)
 |      Weibull distribution.
 |      
 |      alpha is the scale parameter and beta is the shape parameter.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  VERSION = 3
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _random.Random:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  getrandbits(...)
 |      getrandbits(k) -> x.  Generates a long int with k random bits.
 |  
 |  jumpahead(...)
 |      jumpahead(int) -> None.  Create new state from existing state and integer.
 |  
 |  random(...)
 |      random() -> x in the interval [0, 1).
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from _random.Random:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

class SystemRandom(Random)
 |  Alternate random number generator using sources provided
 |  by the operating system (such as /dev/urandom on Unix or
 |  CryptGenRandom on Windows).
 |  
 |   Not available on all systems (see os.urandom() for details).
 |  
 |  Method resolution order:
 |      SystemRandom
 |      Random
 |      _random.Random
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  getrandbits(self, k)
 |      getrandbits(k) -> x.  Generates a long int with k random bits.
 |  
 |  getstate = _notimplemented(self, *args, **kwds)
 |  
 |  jumpahead = _stub(self, *args, **kwds)
 |  
 |  random(self)
 |      Get the next random number in the range [0.0, 1.0).
 |  
 |  seed = _stub(self, *args, **kwds)
 |  
 |  setstate = _notimplemented(self, *args, **kwds)
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from Random:
 |  
 |  __getstate__(self)
 |  
 |  __init__(self, x=None)
 |      Initialize an instance.
 |      
 |      Optional argument x controls seeding, as for Random.seed().
 |  
 |  __reduce__(self)
 |  
 |  __setstate__(self, state)
 |  
 |  betavariate(self, alpha, beta)
 |      Beta distribution.
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |      Returned values range between 0 and 1.
 |  
 |  choice(self, seq)
 |      Choose a random element from a non-empty sequence.
 |  
 |  expovariate(self, lambd)
 |      Exponential distribution.
 |      
 |      lambd is 1.0 divided by the desired mean.  It should be
 |      nonzero.  (The parameter would be called "lambda", but that is
 |      a reserved word in Python.)  Returned values range from 0 to
 |      positive infinity if lambd is positive, and from negative
 |      infinity to 0 if lambd is negative.
 |  
 |  gammavariate(self, alpha, beta)
 |      Gamma distribution.  Not the gamma function!
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |  
 |  gauss(self, mu, sigma)
 |      Gaussian distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.  This is
 |      slightly faster than the normalvariate() function.
 |      
 |      Not thread-safe without a lock around calls.
 |  
 |  lognormvariate(self, mu, sigma)
 |      Log normal distribution.
 |      
 |      If you take the natural logarithm of this distribution, you'll get a
 |      normal distribution with mean mu and standard deviation sigma.
 |      mu can have any value, and sigma must be greater than zero.
 |  
 |  normalvariate(self, mu, sigma)
 |      Normal distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.
 |  
 |  paretovariate(self, alpha)
 |      Pareto distribution.  alpha is the shape parameter.
 |  
 |  randint(self, a, b)
 |      Return random integer in range [a, b], including both end points.
 |  
 |  randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, 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.
 |      Do not supply the 'int', 'default', and 'maxwidth' arguments.
 |  
 |  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)
 |  
 |  shuffle(self, x, random=None, int=<type 'int'>)
 |      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.
 |  
 |  triangular(self, low=0.0, high=1.0, mode=None)
 |      Triangular distribution.
 |      
 |      Continuous distribution bounded by given lower and upper limits,
 |      and having a given mode value in-between.
 |      
 |      http://en.wikipedia.org/wiki/Triangular_distribution
 |  
 |  uniform(self, a, b)
 |      Get a random number in the range [a, b) or [a, b] depending on rounding.
 |  
 |  vonmisesvariate(self, mu, kappa)
 |      Circular data distribution.
 |      
 |      mu is the mean angle, expressed in radians between 0 and 2*pi, and
 |      kappa is the concentration parameter, which must be greater than or
 |      equal to zero.  If kappa is equal to zero, this distribution reduces
 |      to a uniform random angle over the range 0 to 2*pi.
 |  
 |  weibullvariate(self, alpha, beta)
 |      Weibull distribution.
 |      
 |      alpha is the scale parameter and beta is the shape parameter.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from Random:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from Random:
 |  
 |  VERSION = 3
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _random.Random:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from _random.Random:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

class WichmannHill(Random)
 |  Method resolution order:
 |      WichmannHill
 |      Random
 |      _random.Random
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  getstate(self)
 |      Return internal state; can be passed to setstate() later.
 |  
 |  jumpahead(self, n)
 |      Act as if n calls to random() were made, but quickly.
 |      
 |      n is an int, greater than or equal to 0.
 |      
 |      Example use:  If you have 2 threads and know that each will
 |      consume no more than a million random numbers, create two Random
 |      objects r1 and r2, then do
 |          r2.setstate(r1.getstate())
 |          r2.jumpahead(1000000)
 |      Then r1 and r2 will use guaranteed-disjoint segments of the full
 |      period.
 |  
 |  random(self)
 |      Get the next random number in the range [0.0, 1.0).
 |  
 |  seed(self, a=None)
 |      Initialize internal state from hashable object.
 |      
 |      None or no argument seeds from current time or from an operating
 |      system specific randomness source if available.
 |      
 |      If a is not None or an int or long, hash(a) is used instead.
 |      
 |      If a is an int or long, a is used directly.  Distinct values between
 |      0 and 27814431486575L inclusive are guaranteed to yield distinct
 |      internal states (this guarantee is specific to the default
 |      Wichmann-Hill generator).
 |  
 |  setstate(self, state)
 |      Restore internal state from object returned by getstate().
 |  
 |  whseed(self, a=None)
 |      Seed from hashable object's hash code.
 |      
 |      None or no argument seeds from current time.  It is not guaranteed
 |      that objects with distinct hash codes lead to distinct internal
 |      states.
 |      
 |      This is obsolete, provided for compatibility with the seed routine
 |      used prior to Python 2.1.  Use the .seed() method instead.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  VERSION = 1
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from Random:
 |  
 |  __getstate__(self)
 |  
 |  __init__(self, x=None)
 |      Initialize an instance.
 |      
 |      Optional argument x controls seeding, as for Random.seed().
 |  
 |  __reduce__(self)
 |  
 |  __setstate__(self, state)
 |  
 |  betavariate(self, alpha, beta)
 |      Beta distribution.
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |      Returned values range between 0 and 1.
 |  
 |  choice(self, seq)
 |      Choose a random element from a non-empty sequence.
 |  
 |  expovariate(self, lambd)
 |      Exponential distribution.
 |      
 |      lambd is 1.0 divided by the desired mean.  It should be
 |      nonzero.  (The parameter would be called "lambda", but that is
 |      a reserved word in Python.)  Returned values range from 0 to
 |      positive infinity if lambd is positive, and from negative
 |      infinity to 0 if lambd is negative.
 |  
 |  gammavariate(self, alpha, beta)
 |      Gamma distribution.  Not the gamma function!
 |      
 |      Conditions on the parameters are alpha > 0 and beta > 0.
 |  
 |  gauss(self, mu, sigma)
 |      Gaussian distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.  This is
 |      slightly faster than the normalvariate() function.
 |      
 |      Not thread-safe without a lock around calls.
 |  
 |  lognormvariate(self, mu, sigma)
 |      Log normal distribution.
 |      
 |      If you take the natural logarithm of this distribution, you'll get a
 |      normal distribution with mean mu and standard deviation sigma.
 |      mu can have any value, and sigma must be greater than zero.
 |  
 |  normalvariate(self, mu, sigma)
 |      Normal distribution.
 |      
 |      mu is the mean, and sigma is the standard deviation.
 |  
 |  paretovariate(self, alpha)
 |      Pareto distribution.  alpha is the shape parameter.
 |  
 |  randint(self, a, b)
 |      Return random integer in range [a, b], including both end points.
 |  
 |  randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, 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.
 |      Do not supply the 'int', 'default', and 'maxwidth' arguments.
 |  
 |  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)
 |  
 |  shuffle(self, x, random=None, int=<type 'int'>)
 |      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.
 |  
 |  triangular(self, low=0.0, high=1.0, mode=None)
 |      Triangular distribution.
 |      
 |      Continuous distribution bounded by given lower and upper limits,
 |      and having a given mode value in-between.
 |      
 |      http://en.wikipedia.org/wiki/Triangular_distribution
 |  
 |  uniform(self, a, b)
 |      Get a random number in the range [a, b) or [a, b] depending on rounding.
 |  
 |  vonmisesvariate(self, mu, kappa)
 |      Circular data distribution.
 |      
 |      mu is the mean angle, expressed in radians between 0 and 2*pi, and
 |      kappa is the concentration parameter, which must be greater than or
 |      equal to zero.  If kappa is equal to zero, this distribution reduces
 |      to a uniform random angle over the range 0 to 2*pi.
 |  
 |  weibullvariate(self, alpha, beta)
 |      Weibull distribution.
 |      
 |      alpha is the scale parameter and beta is the shape parameter.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from Random:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _random.Random:
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  getrandbits(...)
 |      getrandbits(k) -> x.  Generates a long int with k random bits.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from _random.Random:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T