创建随机字母数组:Python 3

sar*_*nns 2 python loops numpy python-3.x

使用下面的函数可以更方便地创建随机整数数组.

def generate_random_strings(x, i, j):

    return np.random.randint(0, 2, size=[x, i, j]).astype(np.float32)

print (generate_random_strings(3, 5, 4))

[[[0. 0. 0. 0.]
[0. 1. 1. 0.]
[0. 1. 1. 0.]
[0. 0. 0. 1.]
[0. 1. 0. 1.]]

[[0. 1. 0. 0.]
[1. 0. 1. 1.]
[0. 1. 1. 0.]
[1. 0. 1. 0.]
[0. 0. 0. 0.]]

[[0. 0. 1. 0.]
[1. 0. 1. 1.]
[0. 0. 0. 1.]
[0. 1. 0. 0.]
[1. 1. 0. 0.]]]
Run Code Online (Sandbox Code Playgroud)

我尝试为字母(az)而不是整数构建类似的函数,但我找不到numpy或任何其他可用库的任何内置函数.

所以我用3 - for循环如下,

# Generate random letter
def randomword(len):
    return random.choice(string.ascii_lowercase)

x= 3
i= 5
j= 4

buf = []

for _ in range(x):
    bu = []
    for i in range(i):
        b = []
        for j in range(j):
            b.append(randomword(1))
        bu.append(b)
    buf.append(np.asarray(bu))

print(np.asarray(buf))

[[['u' 'w' 'w' 'x']
  ['b' 's' 'p' 'a']
  ['k' 'u' 'y' 'p']
  ['p' 'z' 'b' 'u']
  ['o' 'h' 'c' 'm']]

 [['t' 'y' 'b' 'r']
  ['e' 's' 'e' 't']
  ['p' 'n' 'd' 'w']
  ['h' 'f' 'i' 'e']
  ['o' 'b' 'q' 'r']]

 [['x' 'z' 'd' 'x']
  ['r' 'b' 'f' 'b']
  ['d' 'h' 'e' 'g']
  ['p' 'g' 'u' 'x']
  ['k' 'j' 'z' 'd']]]
Run Code Online (Sandbox Code Playgroud)

那么,现在我的问题是,是否存在np.random.randint()字符串/字母的任何函数,如果没有,是否有任何pythonic方法来减少(for循环)代码长度.

lll*_*lll 8

您可以使用numpy.choice所有ascii小写字母:

import string
import numpy as np

np.random.choice(list(string.ascii_lowercase),  size=(3, 5,4))
Run Code Online (Sandbox Code Playgroud)