Kotlin:如何从指定索引开始循环遍历固定长度列表?
从指定索引循环遍历列表的实现方案
核心思路是利用模运算计算遍历位置:通过 (起始索引 + 偏移量) % 列表长度 来获取当前遍历的索引,以此实现从指定起点出发,绕列表一圈后回到起点的循环遍历;如果需要动态设置结束位置,只需在遍历过程中判断当前索引是否等于目标结束索引即可终止。
Python 实现
完整遍历(回到起点)
def cyclic_traverse(lst, start_idx): length = len(lst) for offset in range(length): current_idx = (start_idx + offset) % length yield lst[current_idx] # 测试示例 my_list = [0, 1, 2, 3, 4, 5, 6, 7] start = 5 for item in cyclic_traverse(my_list, start): print(item, end=' ') # 输出:5 6 7 0 1 2 3 4
动态设置结束位置
def cyclic_traverse_until(lst, start_idx, end_idx): length = len(lst) current_idx = start_idx while True: yield lst[current_idx] if current_idx == end_idx: break current_idx = (current_idx + 1) % length # 测试:从索引5开始,到索引2结束 for item in cyclic_traverse_until(my_list, 5, 2): print(item, end=' ') # 输出:5 6 7 0 1 2
Java 实现
完整遍历(回到起点)
import java.util.List; public class CyclicTraversal { public static void cyclicTraverse(List<Integer> list, int startIdx) { int length = list.size(); for (int offset = 0; offset < length; offset++) { int currentIdx = (startIdx + offset) % length; System.out.print(list.get(currentIdx) + " "); } } public static void main(String[] args) { List<Integer> myList = List.of(0, 1, 2, 3, 4, 5, 6, 7); int start = 5; cyclicTraverse(myList, start); // 输出:5 6 7 0 1 2 3 4 } }
动态设置结束位置
import java.util.List; public class CyclicTraversalUntil { public static void cyclicTraverseUntil(List<Integer> list, int startIdx, int endIdx) { int length = list.size(); int currentIdx = startIdx; while (true) { System.out.print(list.get(currentIdx) + " "); if (currentIdx == endIdx) { break; } currentIdx = (currentIdx + 1) % length; } } public static void main(String[] args) { List<Integer> myList = List.of(0, 1, 2, 3, 4, 5, 6, 7); cyclicTraverseUntil(myList, 5, 2); // 输出:5 6 7 0 1 2 } }
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

