在takewhi的lambda函数中使用参数

2024-04-27 22:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力熟悉itertools。作为练习,我尝试生成满足-1<;y<;x<;5的(x,y)整数对。使用itertools的以下代码产生不正确的结果:

from itertools import *
xs = xrange(0,5)
allPairs = chain(*(izip(repeat(x), takewhile(lambda y: y < x, count())) for x in xs))
print list(allPairs)

输出为

[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3), (4, 0), (4, 1), (4, 2), (4, 3)]

问题似乎是takewhile中的lambda函数使用的是x=4,即范围内的最大值。你知道吗

如果我修改上面的代码,为每个x显式地构造一个lambda函数,如下所示,那么输出的计算是正确的。你知道吗

from itertools import *
xs = xrange(0,5)
xypair = lambda x: izip(repeat(x), takewhile(lambda y: y < x, count()))

allPairs = chain(*(xypair(x) for x in xs))
print list(allPairs)

输出:

[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3)]

你知道为什么在第一个代码中,lambda只使用xs上迭代的最后一个值来构造吗?你知道吗


Tags: lambda代码fromimportltchainforcount
1条回答
网友
1楼 · 发布于 2024-04-27 22:35:41

尝试简单一点的方法:

combinations(iterable,r): r-length tuples, in sorted order, no repeated elements

>>> list(combinations(xrange(0,5),2))
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

相关问题 更多 >