Python中的iter()、next()、repeat()和iter.get_next()

iter()、next()

通过一个例子进行说明。

array = np.array([1, 2, 3, 4, 5])
it = iter(array)

此时相当于建立了一个迭代器it,当调用it中的数时,需要使用next()函数,即:

next(it)

连续执行该条语句5次,结果分别为1,2,3,4,5,如果再执行一次,则会报错,如下:

StopIteration                             Traceback (most recent call last)
<ipython-input-57-bc1ab118995a> in <module>
----> 1 next(it)

StopIteration: 

这说明it中的所有数字都已经被取出,再执行next(it)函数时,it里已经没有数可取出了,所以报错。
在以上代码中,array是可迭代对象,it是迭代器,判断是不是可迭代对象或迭代器的方法为:

import collections
a = [1,2,3]
isinstance(a, collections.Iterable)
isinstance(a, collections.Iterator)

一个很常见的应用就是:Python在处理列表的时候,是直接把整个列表读进内存的,当遇到大量样本时的时候会变得很慢。而迭代器的优势在于只把需要的元素读进内存,因此占用内存更少。

repeat()、iter.get_next()

使用repeat可以对原始数据进行扩充。
如:

array = np.array([1, 2, 3])
dataset = array.repeat(2)

则dataset为:

[1, 1, 2, 2, 3, 3]

但如果原始数据是tensor类型,repeat之后得到的是[1, 2, 3, 1, 2, 3]。
如:

x = np.array([1, 2, 3, 4, 5, 6])
dataset = tf.data.Dataset.from_tensor_slices(x)
dataset = dataset.shuffle(2) # 将数据打乱,数值越大,混乱程度越大
dataset = dataset.batch(4) # 按照顺序取出4行数据,最后一次输出可能小于batch
dataset = dataset.repeat() # 数据集重复了指定次数
iter_ = iter(dataset)

此时要调用iter.get_next()而不是next()。

el = iter_.get_next()
el
发布了116 篇原创文章 · 获赞 13 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_36758914/article/details/104650834