如何使用itertools迭代python中具有不同长度的iterables?

时间:2014-01-23 12:13:32

标签: python itertools

我有两个不同长度的迭代,如下所示

  range(5)
  numpy.arange(0,0.3,0.1)

我希望有如下配对

    (0,0.)
    (1,0.)
    (2,0.)
    (3,0.)
    (4,0.)

    (0,0.1)
    (1,0.1)
    (2,0.1)
    (3,0.1)
    (4,0.1)

    (0,0.2)
    (1,0.2)
    (2,0.2)
    (3,0.2)
    (4,0.2)

如何使用itertools做到这一点?

1 个答案:

答案 0 :(得分:4)

通常是itertools.product的工作:

>>> from itertools import product
>>> for x in product(range(5), numpy.arange(0, 0.3, 0.1)):
    print x
...     
(0, 0.0)
(0, 0.10000000000000001)
(0, 0.20000000000000001)
(1, 0.0)
(1, 0.10000000000000001)
(1, 0.20000000000000001)
(2, 0.0)
(2, 0.10000000000000001)
(2, 0.20000000000000001)
(3, 0.0)
(3, 0.10000000000000001)
(3, 0.20000000000000001)
(4, 0.0)
(4, 0.10000000000000001)
(4, 0.20000000000000001)

由于您需要“其他”订单,因此您可以使用理解:

>>> [(x,y) for y in numpy.arange(0, 0.3, 0.1) for x in range(5)]

[(0, 0.0),
 (1, 0.0),
 (2, 0.0),
 (3, 0.0),
 (4, 0.0),
 (0, 0.10000000000000001),
 (1, 0.10000000000000001),
 (2, 0.10000000000000001),
 (3, 0.10000000000000001),
 (4, 0.10000000000000001),
 (0, 0.20000000000000001),
 (1, 0.20000000000000001),
 (2, 0.20000000000000001),
 (3, 0.20000000000000001),
 (4, 0.20000000000000001)]

或者你可以反转参数然后反转itertools.product吐出的每个元组(它们总是以最快的速度循环最右边的元素)。

>>> [x[::-1] for x in product(numpy.arange(0, 0.3, 0.1), range(5))]

[(0, 0.0),
 (1, 0.0),
 (2, 0.0),
 (3, 0.0),
 (4, 0.0),
 (0, 0.10000000000000001),
 (1, 0.10000000000000001),
 (2, 0.10000000000000001),
 (3, 0.10000000000000001),
 (4, 0.10000000000000001),
 (0, 0.20000000000000001),
 (1, 0.20000000000000001),
 (2, 0.20000000000000001),
 (3, 0.20000000000000001),
 (4, 0.20000000000000001)]