快速生成随机字符串序列的方法

时间:2015-05-06 18:47:59

标签: python random

我有一个函数,它返回一个大小为N的字符串,其中包含一个随机字符序列,形成一个小集合{A,B,C,D}。我生成这一行:

def gen_line(N):
  tline = ""
  for i in range(N):
    xrand = random.random()
    if( xrand < 0.25 ):
      ch = "A" 
    elif( xrand < 0.50 ):
      ch = "B" 
    elif( xrand < 0.75 ):
      ch = "C" 
    elif( xrand < 1.00 ):
      ch = "D" 
    else:
      print "ERROR: xrand = %f"%( xrand )
    tline = tline+ch
  return tline

但毫无疑问,这是一种非常低效的做事方式。有没有更好,更pythonic的方法来实现这个目标?

2 个答案:

答案 0 :(得分:2)

尝试将random.choicestr.join一起使用。

>>> x = 'abcd'
>>> ''.join(random.choice(x) for _ in range(10))
'aabbdbadbc'

答案 1 :(得分:0)

您可以使用np.random.choice

In [13]:

import random
a = np.array(list('abcd'))
%timeit ''.join(np.random.choice(a, 10000))
​
def gen_line(N):
  tline = ""
  for i in range(N):
    xrand = random.random()
    if( xrand < 0.25 ):
      ch = "A" 
    elif( xrand < 0.50 ):
      ch = "B" 
    elif( xrand < 0.75 ):
      ch = "C" 
    elif( xrand < 1.00 ):
      ch = "D" 
    else:
      print("ERROR: xrand = %f"%( xrand ))
    tline = tline+ch
  return tline
​
%timeit gen_line(10000)
100 loops, best of 3: 6.39 ms per loop
100 loops, best of 3: 11.7 ms per loop
相关问题