简体   繁体   English

将列表包装为切片操作

[英]Wrapping around a list as a slice operation

Consider the following simple python code考虑以下简单的python代码

>>> 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):向左旋转n元素(或向右旋转负 n):

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

Note that collections.deque has support for rotations .请注意, collections.deque支持旋转 It might be better to use that instead of lists.使用它而不是列表可能会更好。

Left:剩下:

L[:1], L[1:] = L[-1:], L[:-1]

Right:对:

L[-1:], L[:-1] = L[:1], L[1:]

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.要进行您描述的包装,您需要更改起始索引和结束索引。

  • A positive starting index cuts away some of initial items.正的起始指数会削减一些初始项目。
  • A negative starting index gives you some of the tail items, cutting initial items again.负起始索引为您提供一些尾部项目,再次切割初始项目。
  • A positive finishing index cuts away some of the tail items.积极的整理指数削减了一些尾部项目。
  • A negative finishing index gives you some of the initial items, cutting tail items again.负整理指数为您提供一些初始项目,再次切割尾部项目。

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 (eg in a loop).如果您需要顺序访问(例如在循环中),请参阅上面的答案,另请参阅itertools.islice.chain以了解无复制顺序方法。

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.如果您不太依赖于精确的切片语法,您可以编写一个函数来产生所需的输出,包括包装行为。

Eg, like this:例如,像这样:

def wrapping_slice(lst, *args):
    return [lst[i%len(lst)] for i in range(*args)]

Example output:示例输出:

>>> L = range(3)
>>> wrapping_slice(L, 1, 4)
[1, 2, 0]
>>> wrapping_slice(L, -1, 4)
[2, 0, 1, 2, 0]
>>> wrapping_slice(L, -1, 4, 2)
[2, 1, 0]

Caveat: You can't use this on the left-hand side of a slice assignment .警告:您不能在切片分配的左侧使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM