将列表环绕为切片操作
考虑下面的简单 python 代码
>>> L = range(3)
>>> L
[0, 1, 2]
我们可以按如下方式对该数组进行切片:
>>> L[1:3]
[1, 2]
向左移动来环绕上面的数组?
[1, 2, 0]
有没有办法通过简单地使用切片操作
Consider the following simple python code
>>> L = range(3)
>>> L
[0, 1, 2]
We can take slices of this array as follows:
>>> L[1:3]
[1, 2]
Is there any way to wrap around the above array by shifting to the left
[1, 2, 0]
by simply using slice operations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
向左旋转 n 个元素(或向右旋转负 n):
请注意 collections.deque 支持轮换 。使用它而不是列表可能会更好。
Rotate left
n
elements (or right for negative n):Note that collections.deque has support for rotations. It might be better to use that instead of lists.
左:
右:
Left:
Right:
在我看来,没有办法,除非您同意如上所示剪切和连接列表。
要进行您所描述的包装,您需要更改起始索引和结束索引。
这些的组合都不能提供尾项后面跟着初始项的包装点。所以无法创建整个事物。
存在许多解决方法。如果您需要顺序访问(例如在循环中),请参阅上面的答案,另请参阅
itertools.islice
和.chain
以了解无复制顺序方法。To my mind, there's no way, unless you agree to cut and concatenate lists as shown above.
To make the wrapping you describe you need to alter both starting and finishing index.
No combination of these can provide the wrapping point where tail items are followed by initial items. So the entire thing can't be created.
Numerous workarounds exist. See answers above, see also
itertools.islice
and.chain
for a no-copy sequential approach if sequential access is what you need (e.g. in a loop).如果您不太执着于精确的切片语法,则可以编写一个函数来生成所需的输出(包括包装行为)。
例如,如下所示:
示例输出:
警告:您不能在切片分配的左侧使用此内容。
If you are not overly attached to the exact slicing syntax, you can write a function that produces the desired output including the wrapping behavior.
E.g., like this:
Example output:
Caveat: You can't use this on the left-hand side of a slice assignment.