Cartesian product of 2 ranges in python
本问题已经有最佳答案,请猛点这里访问。
您知道如何在python中循环100和200的笛卡尔积,例如:
1 2 3 4 5 6 7 8 9 10 11 12 | for cartesian(100,200): print result 1,1 1,2 . . . 123,197 . . 100,200 |
1 2 3 | from itertools import product for j in product(range(100), range(200)): print j |
或者,从产品文档中:
Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
也许我遗漏了一些东西,但不是像这样简单吗:
1 2 3 | for i in range(100): for j in range(200): print i, j |
稍微优化的版本:
1 2 3 4 | inner_range = range(200) for i in range(100): for j in inner_range: print i, j |