在python 3中将地图对象转换为numpy数组 [英] Convert map object to numpy array in python 3
本文介绍了在python 3中将地图对象转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python 2中,我可以执行以下操作:
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]
在Python 3中,它不再起作用:
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>
如何获得旧的行为(将map
结果转换为numpy
数组)?
How do I get the old behaviour (converting the map
results to numpy
array)?
编辑:正如@jonrsharpe在他的回答中指出的,如果我先将seq
转换为列表,则可以解决此问题:
Edit: As @jonrsharpe pointed out in his answer this could be fixed if I converted seq
to a list first:
seq = np.array(list(seq))
但是我希望避免额外调用list
.
but I would prefer to avoid the extra call to list
.
推荐答案
除了@jonrsharpe已经指出的有效解决方案之外,还有另一种选择是使用
One more alternative, other than the valid solutions @jonrsharpe already pointed out is to use np.fromiter
:
>>> import numpy as np
>>> f = lambda x: x**2
>>> seq = map(f, range(5))
>>> np.fromiter(seq, dtype=np.int)
array([ 0, 1, 4, 9, 16])
这篇关于在python 3中将地图对象转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文