gpt4 book ai didi

numpy - 如何反转 numpy.roll?

转载 作者:行者123 更新时间:2023-12-02 00:07:11 26 4
gpt4 key购买 nike

我有一个重复调用 rollfor 循环,我想反转创建数组的顺序。

我想我忽略了一些琐碎的方法来做到这一点,但到目前为止我只找到了 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]

最佳答案

怎么样

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]

一直滚动所有内容(除了一个)并在第一卷之前打印(所以第一行的 crange(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]

关于numpy - 如何反转 numpy.roll?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com