简体   繁体   English

Python:有没有办法从一个特定的索引循环遍历一个列表,然后再回到前面?

[英]Python: Is there a way to loop through a list from a specific index that wraps back to the front onwards?

Is there a way to loop through a list from a specific index that wraps back to the front?有没有办法从一个特定的索引循环遍历一个列表,然后返回到前面?

let's imagine a list让我们想象一个列表

arr = [0,1,2,3,4,5,6,7,8,9]

is there a way to loop from 4 onwards, wrapping back to the front and continuing from there?有没有办法从4开始循环,回到前面并从那里继续?

expected output预计 output

4 5 6 7 8 9 0 1 2 3

Visualized example可视化示例

There is.有。 You can slice the list in two and iterate over them in the same loop like this:您可以将列表一分为二并在同一个循环中迭代它们,如下所示:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
idx = 4
for i in arr[idx:] + arr[:idx]:
    print(i)

If you want to use the iterator directly, then you can use如果你想直接使用迭代器,那么你可以使用

[x for x in arr[4:] + arr[:4]]

Otherwise if you use indices:否则,如果您使用索引:

[arr[(4 + i)%len(arr)] for i in range(len(arr))]

The examples produce a new list, but the idea is here这些示例产生了一个新列表,但想法就在这里

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

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