将列表包装为切片操作 [英] Wrapping around a list as a slice operation

查看:40
本文介绍了将列表包装为切片操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单的python代码

<预><代码>>>>L = 范围(3)>>>升[0, 1, 2]

我们可以按如下方式对这个数组进行切片:

<预><代码>>>>L[1:3][1, 2]

有没有办法通过左移来环绕上面的数组

[1, 2, 0]

简单地使用切片操作?

解决方案

向左旋转 n 个元素(或向右旋转 n 个元素):

L = L[n:] + L[:n]

请注意,collections.deque 支持 旋转.使用它而不是列表可能会更好.

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?

解决方案

Rotate left n elements (or right for negative n):

L = L[n:] + L[:n]

Note that collections.deque has support for rotations. It might be better to use that instead of lists.

这篇关于将列表包装为切片操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆