首页 > 解决方案 > Using list() on cycle object hangs system

问题描述

I'm trying to cycle through the elements of an array aa, where the for block is not applied over it but over another array bb.

import numpy as np
from itertools import cycle

aa = np.array([[399., 5., 9.], [9., 35., 2.], [.6, 15., 8842.]])
c_aa = cycle(aa)

bb = np.array([33, 1., 12, 644, 234, 77, 194, 70])
for _ in bb:
    print(c_aa)

This does not work, it simply outputs:

<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>

But if I change that last line for print(list(c_aa)) my entire system almost hangs.

What is going on here and how can I iterate over aa without using it in the for call?

标签: pythonnumpyitertoolscycle

解决方案


您需要实际迭代循环,例如:

for b, a_row in zip(bb, cycle(aa)):
  print(b, a_row)

输出:

33.0 [399.   5.   9.]
1.0 [ 9. 35.  2.]
12.0 [6.000e-01 1.500e+01 8.842e+03]
644.0 [399.   5.   9.]
234.0 [ 9. 35.  2.]
77.0 [6.000e-01 1.500e+01 8.842e+03]
194.0 [399.   5.   9.]
70.0 [ 9. 35.  2.]

演示


推荐阅读