Python 在takewhile的lambda函数中使用参数
我正在努力熟悉itertools。作为练习,我尝试生成满足-1Python 在takewhile的lambda函数中使用参数,python,itertools,Python,Itertools,我正在努力熟悉itertools。作为练习,我尝试生成满足-1
谢谢你指出相关的问题和答案。谢谢。这个想法很有趣。然而,我正在寻找python行为的解释,以便更好地理解python。
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)]
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)]
>>> 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)]