地圖應該比列表比較快一點:
import numpy as np
arr = np.array(map(int,'00101'))
一些時序顯示它是1024個字符的字符串:
In [12]: timeit np.array([int(c) for c in s])
1000 loops, best of 3: 422 µs per loop
In [13]: timeit np.array(map(int,s))
1000 loops, best of 3: 389 µs per loop
只需調用s中的列表並使用dtype = int就會更快:
In [20]: timeit np.array(list(s), dtype=int)
1000 loops, best of 3: 329 µs per loop
使用fromiter又一次更快的傳遞dtype=int
是:
In [21]: timeit np.fromiter(s,dtype=int)
1000 loops, best of 3: 289 µs per loop
借用這個answer,使用fromstring和UINT8爲D型是最快的:
In [54]: timeit np.fromstring(s, 'int8') - 48
100000 loops, best of 3: 4.54 µs per loop
即使重新綁定的名稱和改變dtype仍然是最快的:
In [71]: %%timeit
....: arr = np.fromstring(s, 'int8') - 48
....: arr = arr.astype(int)
....:
100000 loops, best of 3: 6.23 µs per loop
甚至比快得多阿什維尼的加入:
In [76]: timeit np.fromstring(' '.join(s), sep=' ', dtype=int)
10000 loops, best of 3: 62.6 µs per loop
由於@Unutbu註釋掉,np.fromstring(s, 'int8') - 48
不限於一和零,但將所有的ASCII數字組成的字符串工作。
什麼是'lambda'呢?只需使用'int' –