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]

一直滚动所有内容(但一个),并在第一卷之前打印(所以你得到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 回答
0

Fwiw,一个不同的问题:要反转np.rollaxis,我发现只有这个,使用 transpose

import numpy as np

a = np.ones((3,4,5,6))
print a.shape

for ax in range( a.ndim ):
    print "ax %d:" % ax ,
    jtrans = np.arange( a.ndim )
    jtrans[0], jtrans[ax] = jtrans[ax], jtrans[0]
    b = a.transpose( jtrans )
    print b.shape, jtrans ,
    a = b.transpose( jtrans )  # and back
    print a.shape

# (3, 4, 5, 6)
# ax 0: (3, 4, 5, 6) [0 1 2 3] (3, 4, 5, 6)
# ax 1: (4, 3, 5, 6) [1 0 2 3] (3, 4, 5, 6)
# ax 2: (5, 4, 3, 6) [2 1 0 3] (3, 4, 5, 6)
# ax 3: (6, 4, 5, 3) [3 1 2 0] (3, 4, 5, 6)
于 2013-12-03T11:14:19.077 回答