3

for-loop繰り返し呼び出す がありroll、作成された配列の順序を逆にしたい。

私はそれを行ういくつかの些細な方法を見落としたと思いますが、これまでのところ、それを行わない方法を10000 3 5 しか見つけていません。

In [1]: from numpy import roll  
In [2]: c = range(5)

## The code I want to invert
In [3]: for i in range(len(c)):
   ...:         c = roll(c, 1)
   ...:         print c
[4 0 1 2 3]
[3 4 0 1 2]
[2 3 4 0 1]
[1 2 3 4 0]
[0 1 2 3 4]    

## The result I want
[0 1 2 3 4]
[1 2 3 4 0]
[2 3 4 0 1]
[3 4 0 1 2]    
[4 0 1 2 3]    


## What I've tried:
In [4]: for i in range(len(c)):
   ...:         c = roll(c, -1)
   ...:         print c
[1 2 3 4 0]
[2 3 4 0 1] # <- false
[3 4 0 1 2]
[4 0 1 2 3]
[0 1 2 3 4]    
In [5]: for i in reversed(range(len(c))):
   ...:         c = roll(c, -i)
   ...:         print c
[4 0 1 2 3] # <- false
[2 3 4 0 1]
[4 0 1 2 3]
[0 1 2 3 4]
[0 1 2 3 4]    

In [6]: for i in reversed(range(len(c))):
        c = roll(c, i)
        print c
   ...:     
[1 2 3 4 0]
[3 4 0 1 2] # <- false
[1 2 3 4 0]
[0 1 2 3 4]
[0 1 2 3 4]

In [7]: for i in range(len(c)):
   ...:    c = roll(c, i)
   ...:    print c
   ...:     
[0 1 2 3 4]
[4 0 1 2 3] # <- false
[2 3 4 0 1]
[4 0 1 2 3]
[0 1 2 3 4]

In [8]: for i in range(len(c)):
   ...:         c = roll(c, -i)
   ...:         print c
   ...:     
[0 1 2 3 4]
[1 2 3 4 0]
[3 4 0 1 2] # <- false
[1 2 3 4 0]
[0 1 2 3 4]
4

2 に答える 2

3

どうですか

for i in range(len(c)):
    print c
    c = roll(c, len(c) - 1)

[0 1 2 3 4]
[1 2 3 4 0]
[2 3 4 0 1]
[3 4 0 1 2]
[4 0 1 2 3]

すべてを丸め (ただし 1 つ)、最初のロールの前に印刷します (つまり、最初の行のようになりますc) range(5)

または、最初に c を印刷すると、最初の解決策でさえ

for i in range(len(c)):
    print c
    c = roll(c, -1)

[0 1 2 3 4]
[1 2 3 4 0]
[2 3 4 0 1]
[3 4 0 1 2]
[4 0 1 2 3]
于 2013-07-12T10:30:09.917 に答える