【发布时间】:2018-08-11 02:59:39
【问题描述】:
使用下面的函数可以更方便地创建一个随机整数数组。
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.]]]
我尝试为字母 (a-z) 而不是整数构建与上述类似的函数,但我无法从 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']]]
所以,现在我的问题是,是否有任何函数作为 np.random.randint() 用于字符串/字母,如果没有,是否有任何 Python 方法来减少(for 循环)代码长度。
【问题讨论】:
-
chr(randint(97, 122))
标签: python python-3.x loops numpy