Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从生成器、列表列表创建numpy数组_Python 3.x_Numpy_Generator - Fatal编程技术网

Python 3.x 从生成器、列表列表创建numpy数组

Python 3.x 从生成器、列表列表创建numpy数组,python-3.x,numpy,generator,Python 3.x,Numpy,Generator,我正在尝试将生成器转换为numpy数组。我对数据列表应用map函数,结果生成一个生成器。我试着做list(map()),然后创建numpy向量,但这需要很长时间。我在某个地方看到,我可以直接使用np.fromiter从生成器创建numpy向量。但是,我遇到了以下错误: ValueError: setting an array element with a sequence. 我发现错误增加是因为我的生成器生成了一个列表列表。比如:[[1,2,3],[4,5,6]我应该为fromiter()函数

我正在尝试将生成器转换为numpy数组。我对数据列表应用map函数,结果生成一个生成器。我试着做
list(map())
,然后创建numpy向量,但这需要很长时间。我在某个地方看到,我可以直接使用
np.fromiter
从生成器创建numpy向量。但是,我遇到了以下错误:

ValueError: setting an array element with a sequence.
我发现错误增加是因为我的生成器生成了一个列表列表。比如:
[[1,2,3],[4,5,6]
我应该为
fromiter()函数使用适当的
dtype
。我找不到一个合适的解释方法来做这件事。你能帮我吗

下面是一个完整的示例:

import numpy as np

def foo(bar):
  return [bar] * 3 # so for 4 it returns [4,4,4], ..

a = [1,2,3,4,5,6,7]
b = map(foo,a)
c = np.fromiter(b, int) # this doesn't work.

要使用复合
dtype
,函数必须返回元组,而不是列表

In [977]: def foo(bar): 
     ...:   return (bar,) * 3 # so for 4 it returns [4,4,4], .. 
     ...:  
     ...: a = [1,2,3,4,5,6,7] 
     ...: b = map(foo,a)                                                                               
In [978]: list(b)                                                                                      
Out[978]: [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7)]
In [979]: def foo(bar): 
     ...:   return (bar,) * 3 # so for 4 it returns [4,4,4], .. 
     ...:  
     ...: a = [1,2,3,4,5,6,7] 
     ...: b = map(foo,a)                                                                               
In [980]: np.fromiter(b, 'i,i,i')                                                                      
Out[980]: 
array([(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6),
       (7, 7, 7)], dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])

请发一张MCVEok。我会尽快编辑帖子。谢谢!所以它并不像我想的那样快。当你把几个发电机串在一起时,发电机是最有用的。它们会延迟评估,但很快或稍后您必须生成所有值。
In [981]: %%timeit b = map(foo,a) 
     ...: np.array(list(b)) 
     ...:  
     ...:                                                                                              
1.9 µs ± 55.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [982]: %%timeit b = map(foo,a) 
     ...: np.fromiter(b, 'i,i,i') 
     ...:  
     ...:                                                                                              
17.2 µs ± 9.72 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)