Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何按一定的顺序迭代?_Python_Loops_For Loop_Iteration_Next - Fatal编程技术网

Python 如何按一定的顺序迭代?

Python 如何按一定的顺序迭代?,python,loops,for-loop,iteration,next,Python,Loops,For Loop,Iteration,Next,我想知道如何在Python中以特定顺序遍历列表 给定列表,lst=[1,3,-1,2],我希望我的函数进行迭代,以便迭代的下一个数字将是当前数字值的索引 lst[0]->lst[1]->lst[3]->lst[2] 1->3->2->-1有几个变量尚未指定: 这应该包括什么样的错误处理 你想让它无限循环吗 假设相应的答案是“无”和“是”,下面是一种方法: def create_iter(arr): i = 0 while True: yield arr[i]

我想知道如何在Python中以特定顺序遍历列表

给定列表,
lst=[1,3,-1,2]
,我希望我的函数进行迭代,以便迭代的下一个数字将是当前数字值的索引

lst[0]->lst[1]->lst[3]->lst[2]
1->3->2->-1

有几个变量尚未指定:

  • 这应该包括什么样的错误处理
  • 你想让它无限循环吗
  • 假设相应的答案是“无”和“是”,下面是一种方法:

    def create_iter(arr):
        i = 0
        while True:
            yield arr[i]
            i = arr[i]
    
    lst = [1,3,-1,2]
    my_iterator = create_iter(lst)
    
    这使得:

    >>> for _ in range(10):
    >>>    print (next(my_iterator))
    1
    3
    2
    -1
    2
    -1
    2
    -1
    2
    -1
    

    假设您检查每个值是否在列表中,但必须具有列表结束条件,则

    index = 0
    while True:
        newindex = mylist[index]
        if newindex >= len(mylist):
            break
        elif newindex == index:
             break
         else:
             index = newindex
    

    请注意,如果列表中的每个条目都是有效的索引,那么您将得到一个无限循环。

    很好,但为什么不在create_iter(lst):print(i)?@zvone中简单地为i执行
    ,因为这会导致无限循环:)好吧,它应该;)请注意,如果某个值位于该值的索引处,则它将继续重复相同的操作value@sabbahillel这是正确的。OP没有指定在这种情况下他想要什么行为,但是添加
    if i==arr[i]:break
    和/或
    try
    块以捕获
    索引器
    这是一个实际需要的问题:为什么要这样做?