反过来切片列表?

时间:2017-06-21 13:05:17

标签: python slice

我有这个清单:

arr = [1, 2, 3, 4, 5, 6]

我想要做的是使用从索引5到索引1的值创建一个新列表。

输出将是:

[6, 1, 2]

这就是我所做的:

output = arr[5:] + arr[:2]

但我想知道是否有另一种切片方式。

就像正常的切片一样,例如:

output = arr[5:1]

但我知道它不会起作用,因为我已经这样做了。请你帮助我好吗?

3 个答案:

答案 0 :(得分:3)

据我所知,在不编写自定义代码的情况下这样做似乎不可能。 Python没有包装列表。

您可以创建自定义生成器来执行您想要的操作:

>>> def cycle(l, start=0):
...     l = l[start:] + l[:start]
...     while True:
...         x = l.pop(0)
...         yield x
...         l.append(x)
... 
>>> k = cycle(a, 5)
>>> next(k)
6
>>> next(k)
1
>>> next(k)
2

示例由于OP的更改后回滚。

这是一个改进版本,它将考虑您希望从生成器获取的数字元素:

>>> def cycle(l, start=0, iters=None):
...     l = l[start:] + l[:start]
...     i = 0
...     while True:
...         if iters is not None and i == iters:
...             raise StopIteration
...         x = l.pop(0)
...         yield x
...         l.append(x)
...         i += 1
... 
>>> a = [1, 2, 3, 4, 5, 6]
>>> list(cycle(a, start=5, iters=3))
[6, 1, 2]

答案 1 :(得分:2)

更新

向左旋转n个元素(或向右旋转负数n)和切割所需元素的数量

L = L[n:] + L[:n] # rotate left n elements

在你的情况下,n是5:

>>> output = arr[5:] + arr[:5]
>>> output[:3]
[6, 1, 2]

>>> arr = [1, 2, 3, 4, 5, 6]
>>> output = arr[:]
>>> del output[2:5]
>>> output
[1, 2, 6]
>>> 

答案 2 :(得分:1)

创建一个函数来为您切割输入数组,并将这两个部分附加在一起以获得所需的列表。

def cyc_slice(lst, start, n): 
    return lst[start:] + lst[:(start+n)%len(lst)]

与其他答案不同,这并不能制作出您不想要的所有列表元素的超级副本。

>>> arr=[1,2,3,4,5,6]
>>> cyc_slice(arr, 5, 3)
[6, 1, 2]

改进的迭代器解决方案:

def cycle(l, start=0, n=None):
    if not l:
        return
    idx = start-1
    end = (idx + n) % len(l) if n else -1
    while idx != end:
        idx+=1
        try:
            x = l[idx]
        except IndexError:
            idx = 0
            x = l[idx]
        yield x

当提供计数时,它将提供许多元素。否则,它可以保持循环。这会遍历列表,因此不会将任何元素分配给内存(除非您从中创建列表)

>>> list(cycle(arr,5,3))
[6, 1, 2]