Python 从最后一个元素链接回列表起始索引的列表返回子列表

Python 从最后一个元素链接回列表起始索引的列表返回子列表,python,list,Python,List,如何从返回3个连续元素的列表中返回子列表,其中最后一个元素链接回列表中的第一个给定索引 例如,给定list=[1,2,3,4,5]的索引3,将返回[4,5,1]。或者给定的索引4和列表=[1,2,3,4,5],将返回[5,1,2] 我有以下选择: 1. return list[index:] + list[:index+3] 2. return list[index:index+3] + list[:len(list)-index] 3. return list[index+3:] + list

如何从返回3个连续元素的列表中返回子列表,其中最后一个元素链接回列表中的第一个给定索引

例如,给定
list=[1,2,3,4,5]
的索引
3
,将返回
[4,5,1]
。或者给定的索引
4
和列表=
[1,2,3,4,5]
,将返回
[5,1,2]

我有以下选择:

1. return list[index:] + list[:index+3]
2. return list[index:index+3] + list[:len(list)-index]
3. return list[index+3:] + list[:len(list)-index]
4. return list[index:index+3] + list[:max(0 , -1*(len(list)-index-3))]
系统的典型用例:

从您给定的选项中,最后一个选项(4.)会产生相同的结果:

lst[i:i+3] + lst[:max(0 , -1*(len(lst)-i-3))]

这一点您只需尝试一下即可轻松确认;)

这可以通过以下方式轻松实现:

您可以从文档中使用:

生成一个迭代器,从iterable返回元素并保存 每份的复印件。当iterable耗尽时,从 保存的副本

代码:

from itertools import cycle, islice

lst = [1, 2, 3, 4, 5]


def get(l, index, length=3):
    return list(islice(cycle(l), index, index + length))


print(get(lst, 3))
print(get(lst, 4))
输出

[4, 5, 1]
[5, 1, 2]
比如:

def return_consecutive(a, index, n=3):
    while index > len(a):
        index -= len(a)
    a.extend(a)
    return a [index:index + n]

return_consecutive(a, 3)
[4, 5, 1]
return_consecutive(a, 4)
[5, 1, 2]
return_consecutive(a, 6)
[2, 3, 4]

这也适用于大于列表长度的值

Im建议使用一种方法,但这需要生成一个比当前列表大两倍的列表

>>> l = [1,2,3,4,5]
>>> def roundlist(l,index,value):
...     return (l+l)[index:index+value]
... 
>>> roundlist(l,3,3)
[4, 5, 1]
>>> roundlist(l,4,3)
[5, 1, 2]

还有其他方法。例如,您可以使用via,然后使用:


如果你已经有了答案,那么你想知道什么?我没有答案。我有很多选择,其中一个是真的。@MayankPorwal问哪种方法最好或者有更好的方法是完全合理的way@Chris_Rands谢谢你能帮我确定哪一个是最合适的选择吗?@AlbinPaul,我不为udemy工作。如果一个问题措词不当或写得不好,这与我的课程中的外部问题无关。他们没有关系。谢谢你的帮助。我想知道,在给定的选项中,哪一个最适合?最后一个是正确的。修正了我的答案。
def return_consecutive(a, index, n=3):
    while index > len(a):
        index -= len(a)
    a.extend(a)
    return a [index:index + n]

return_consecutive(a, 3)
[4, 5, 1]
return_consecutive(a, 4)
[5, 1, 2]
return_consecutive(a, 6)
[2, 3, 4]
>>> l = [1,2,3,4,5]
>>> def roundlist(l,index,value):
...     return (l+l)[index:index+value]
... 
>>> roundlist(l,3,3)
[4, 5, 1]
>>> roundlist(l,4,3)
[5, 1, 2]
from collections import deque
from itertools import islice

L = [1,2,3,4,5]
k, n = -3, 3

dq = deque(L)
dq.rotate(k)
res = list(islice(dq, 0, n))

[4, 5, 1]