懒惰地在Python中转置列表 [英] Lazily transpose a list in Python

查看:127
本文介绍了懒惰地在Python中转置列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个3元组的可迭代生成,它们是惰性生成的.我试图弄清楚如何将其变成3个可迭代对象,分别由元组的第一个,第二个和第三个元素组成.但是,我希望这样做会很懒.

So, I have an iterable of 3-tuples, generated lazily. I'm trying to figure out how to turn this into 3 iterables, consisting of the first, second, and third elements of the tuples, respectively. However, I wish this to be done lazily.

因此,例如,我希望将[(1, 2, 3), (4, 5, 6), (7, 8, 9)]转换为[1, 4, 7][2, 5, 8][3, 6, 9]. (除了我想要的可迭代对象而不是列表.)

So, for example, I wish [(1, 2, 3), (4, 5, 6), (7, 8, 9)] to be turned into [1, 4, 7], [2, 5, 8], [3, 6, 9]. (Except I want iterables not lists.)

标准的zip(*data)惯用语不起作用,因为参数拆包扩展了整个可迭代项. (您可以通过注意到zip(*((x, x+1, x+2) for x in itertools.count(step=3)))挂起来验证这一点.)

The standard zip(*data) idiom doesn't work, because the argument unpacking expands the entire iterable. (You can verify this by noting that zip(*((x, x+1, x+2) for x in itertools.count(step=3))) hangs.)

到目前为止,我想出的最好的方法是:

The best I've come up with thus far is the following:

def transpose(iterable_of_three_tuples):
    teed = itertools.tee(iterable_of_three_tuples, 3)
    return map(lambda e: e[0], teed[0]), map(lambda e: e[1], teed[1]), map(lambda e: e[2], teed[2])

这似乎有效.但这似乎不像是干净的代码.它做了很多不必要的工作.

This seems to work. But it hardly seems like clean code. And it does a lot of what seems to be unnecessary work.

推荐答案

您的transpose正是您所需要的.

使用您选择的任何解决方案,您都必须缓冲未使用的值(例如,要获得7,则必须读取1-6,并将它们存储在内存中,以便其他可迭代对象请求它们) . tee已经完全进行了这种缓冲,因此无需自己实现.

With any solution you'd choose, you'd have to buffer the unused values (e.g. to get to the 7, you have to read 1-6, and store them in memory for when the other iterables ask for them). tee already does exactly that kind of buffering, so there's no need implementing it yourself.

唯一的(次要)问题是我写的略有不同,避免了maplambda s:

The only other (minor) thing is that I'd write it slightly differently, avoiding the map and lambdas:

def transpose(iterable_of_three_tuples):
    teed = itertools.tee(iterable_of_three_tuples, 3)
    return ( e[0] for e in teed[0] ),  ( e[1] for e in teed[1] ),  ( e[2] for e in teed[2] )

这篇关于懒惰地在Python中转置列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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