在Python 2中,我可以执行以下操作:
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]
Run Code Online (Sandbox Code Playgroud)
在Python 3中,它不再起作用了:
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>
Run Code Online (Sandbox Code Playgroud)
如何获得旧行为(将map结果转换为numpy数组)?
编辑:正如@jonrsharpe在他的回答中指出的那样,如果我先转换seq成一个列表,这可以修复:
seq = np.array(list(seq))
Run Code Online (Sandbox Code Playgroud)
但我宁愿避免额外的电话list.
我喜欢使用np.fromiter,numpy因为它是一种构建np.array对象的资源惰性方式.但是,它似乎不支持多维数组,这些数组也非常有用.
import numpy as np
def fun(i):
""" A function returning 4 values of the same type.
"""
return tuple(4*i + j for j in range(4))
# Trying to create a 2-dimensional array from it:
a = np.fromiter((fun(i) for i in range(5)), '4i', 5) # fails
# This function only seems to work for 1D array, trying then:
a = np.fromiter((fun(i) for i in range(5)),
[('', 'i'), ('', 'i'), ('', 'i'), ('', 'i')], 5) …Run Code Online (Sandbox Code Playgroud)