# NumPy 的 Universal 函式

``````for i in 0..256 {
for j in 0..256 {
if i & j == 0 { White } else { Black }
}
}
``````

``````n = 32
for i in range(n):
for j in range(n):
if i & j == 0:
print('■', end = '')
else:
print('　', end = '')
print()
``````

NumPy 的 `arange` 可以指定範圍建立一維陣列，如果想要二維呢？可以建立一個 `n * n` 長度的一維陣列，然後用 `reshape` 將它的形狀改變為 `n x n` 二維陣列：

``````tri = np.arange(n ** 2).reshape(n, n)
``````

``````[[   0    1    2 ...   29   30   31]
[  32   33   34 ...   61   62   63]
[  64   65   66 ...   93   94   95]
...
[ 928  929  930 ...  957  958  959]
[ 960  961  962 ...  989  990  991]
[ 992  993  994 ... 1021 1022 1023]]
``````

NumPy 的 `frompyfunc` 可以接受一個函式，指定該函式輸入引數的個數，輸出結果的個數，傳回 `numpy.ufunc` 實例，你指定的函式只需要關切陣列中每個元素該如何處理就可以了，例如：

``````def bw_symbol(elem, n):
i = elem // n
j = elem % n
return '■' if i & j == 0 else '　'

bw_symbol = np.frompyfunc(bw_symbol, 2, 1)
``````

``````tri = bw_symbol(tri, n)
``````

``````[['■' '■' '■' ... '■' '■' '■']
['■' '\u3000' '■' ... '\u3000' '■' '\u3000']
['■' '■' '\u3000' ... '■' '\u3000' '\u3000']
...
['■' '\u3000' '■' ... '\u3000' '\u3000' '\u3000']
['■' '■' '\u3000' ... '\u3000' '\u3000' '\u3000']
['■' '\u3000' '\u3000' ... '\u3000' '\u3000' '\u3000']]
``````

``````tri = np.apply_along_axis(''.join, 1, tri)
``````

``````println = np.frompyfunc(print, 1, 0)
println(tri)
``````

``````import numpy as np

def bw_symbol(elem, n):
i = elem // n
j = elem % n
return '■' if i & j == 0 else '　'

# 向量化
bw_symbol = np.frompyfunc(bw_symbol, 2, 1)
println = np.frompyfunc(print, 1, 0)

n = 32
tri = np.arange(n ** 2).reshape(n, n)
tri = bw_symbol(tri, n)
tri = np.apply_along_axis(''.join, 1, tri)
println(tri)
``````