如何解压缩迭代器? [英] How to unzip an iterator?

查看:310
本文介绍了如何解压缩迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一对 xys 的对象列表,将其解压缩为两个列表的Python习语是:

Given a list of pairs xys, the Python idiom to unzip it into two lists is:

xs, ys = zip(*xys)

如果 xys 是一个迭代器,如何将其解压缩为两个迭代器,而不将所有内容存储在内存中?

If xys is an iterator, how can I unzip it into two iterators, without storing everything in memory?

推荐答案

假设你有一些可迭代的对:

Suppose you have some iterable of pairs:

a = zip(range(10), range(10))

如果我正确地解释了你的要求,你可以为第一个生成独立的迭代器使用 itertools.tee

If I'm correctly interpreting what you are asking for, you could generate independent iterators for the firsts and seconds using itertools.tee:

 xs, ys = itertools.tee(a)
 xs, ys = (x[0] for x in xs), (y[1] for y in ys)

注意这将在内存中保留您将其中一个与另一个进行迭代的差异。

Note this will keep in memory the "difference" between how much you iterate one of them vs. the other.

这篇关于如何解压缩迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆