如何创建数组数组,以及如何使用numpy引用元素



我试图将生活游戏重新创建为一种练习,但我不知道如何创建矩阵和引用元素。

我试过了,但它只是创建了一个阵列

for col in range(0,width):
for row in range(0,height):
at = np.append(at, 1 if rnd.random() < 0.2 else 0)
array = np.append(a, at)
array_temp = np.array([])

替代NumPy解决方案:

>>> import numpy as np
>>> seed = np.random.random((10,5))
>>> seed
array([[0.43419963, 0.12927612, 0.47783417, 0.6698047 , 0.43966626],
[0.56238954, 0.90856671, 0.84653548, 0.54566383, 0.98273554],
[0.13319855, 0.14511374, 0.44135731, 0.57732303, 0.63272811],
[0.67107476, 0.113417  , 0.25593979, 0.67509295, 0.35349618],
[0.86125898, 0.21895507, 0.46389417, 0.18839496, 0.90046474],
[0.03403771, 0.19303373, 0.02871153, 0.85036184, 0.95387585],
[0.3316397 , 0.84540023, 0.97718179, 0.95335886, 0.9703442 ],
[0.0221273 , 0.7636946 , 0.45536691, 0.64732677, 0.57123722],
[0.40939072, 0.49219486, 0.90310105, 0.12079284, 0.41212587],
[0.26332532, 0.52836011, 0.45873454, 0.69026349, 0.72141677]])
>>> board = np.where(seed < 0.2, 1, 0)
>>> board
array([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 0]])

您可以避免循环,并使用numpy.random.choice生成加权Numpy矩阵

import numpy as np
width = 5
height = 4
np.random.choice(2, [height, width], p=[0.8, .2])

给你类似的东西:

array([[1, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 1, 1],
[0, 0, 0, 0, 0]])

您可以对随机化函数进行矢量化,并将其应用于空矩阵:

import random
import numpy as np
def f(i):
return 1 if random.random() < 0.2 else 0

width = 5
height = 5
result = np.vectorize(f)(np.empty([width, height]))
print(result)

最新更新