「Python」Convert map object to numpy array in python 3

时间:2022-07-04 19:37:22

转自*。备忘用。

Question

In Python 2 I could do the following:

import numpy as np    
f = lambda x: x**2
seq = map(f, xrange(5))
seq = np.array(seq)
print seq
# prints: [ 0  1  4  9 16]

In Python 3 it does not work anymore:

import numpy as np    
f = lambda x: x**2
seq = map(f, range(5))
seq = np.array(seq)
print(seq)
# prints: <map object at 0x10341e310>

How do I get the old behaviour (converting the map results to numpy array)?

Answer

Use np.fromiter:

import numpy as np    
f = lambda x: x**2
seq = map(f, range(5))
np.fromiter(seq, dtype=np.int)
# gets array([ 0,  1,  4,  9, 16])