How can you consume a generator into a typed array?

fromiter consumes an iterable in sequence and constructs a one-dimensional array using the specified dtype.

numpy.fromiter in practice

Convert three text readings to integers as they arrive to avoid an intermediate list. With count set to three the iterator must actually supply three values.

import numpy as np
np.fromiter((int(s) for s in ['7','8','9']), dtype=int, count=3)

Result [7, 8, 9]

中文

如何一次读取生成器里的数值?

fromiter 顺次消费可迭代对象,并按给定 dtype 构造一维数组。

numpy.fromiter 算例

把三条文本读数逐个转为整数,可以省去中间列表。指定 count=3 时必须确有三项,否则读取会报错。

import numpy as np
np.fromiter((int(s) for s in ['7','8','9']), dtype=int, count=3)

结果 [7, 8, 9]

References / 参考来源

Keep reading / 继续阅读