在Python中操纵for循环的索引

在Python中操纵for循环的索引,python,for-loop,indexing,Python,For Loop,Indexing,可以在Python for循环中操作索引指针吗 例如,在PHP中,以下示例将打印13: $test = array(1,2,3,4); for ($i=0; $i < sizeof($test); $i++){ print $test[$i].' '; $i++; } 是否有一种方法可以在循环内操纵for循环指针,以便实现一些复杂的逻辑(例如,返回2步,然后前进3步)?我知道可能有其他方法来实现我的算法(我现在就是这么做的),但我想知道Python是否提供了这种能力 是和

可以在Python for循环中操作索引指针吗

例如,在PHP中,以下示例将打印
13

$test = array(1,2,3,4);
for ($i=0; $i < sizeof($test); $i++){
    print $test[$i].' ';
    $i++;
}

是否有一种方法可以在循环内操纵for循环指针,以便实现一些复杂的逻辑(例如,返回2步,然后前进3步)?我知道可能有其他方法来实现我的算法(我现在就是这么做的),但我想知道Python是否提供了这种能力

是和否。python循环旨在迭代预定义的迭代器,因此不允许直接修改其进度。但您当然可以像在php中一样:

test = ['1', '2', '3', '4']
i = 0
while i < len(test):
    print test[i]
    # Do anything with i here, e.g.
    i = i - 2
    # This is part of the loop
    i = i + 1
test=['1','2','3','4']
i=0
而i
当您尝试操作索引
i
时,您正在进行操作,但是当
for
循环进入下一次迭代时,它会将
i
的下一个值指定给
xrange(len(test))
以便它不会受到您所做操作的影响

您可能希望在执行以下操作时尝试执行

test = ['1', '2', '3', '4']
i = 0
while i < 4:
    print test[i]
    i += 2
test=['1','2','3','4']
i=0
而我<4:
打印测试[i]
i+=2

的语义是

迭代序列元素(如字符串、元组或列表)或其他iterable对象

您可以阅读更多有关的信息


因此,如果您想在访问容器时实现一些逻辑,您应该使用while或其他方法,而不是for

for complex loop logic,您可以设置步长以迭代创建的数组或使用lambda函数

#create an array
a = [3, 14, 8, 2, 7, 5]

#access every other element

for i in range(0, len(a), 2):
    print a[i]

#access every other element backwards

for i in range(len(a) - 1, 0, -2):
    print a[i]

#access every odd numbered index

g = lambda x: 2*x + 1
for i in range(len(a)):
if g(i) > len(a):
        break
else:
        print a[g(i)]

谢谢你的回复,我接受了最老的一个,因为你的解决方案是相似的。是的,当他发布答案时,我正在写答案的文本部分。最好是那些否决这个问题的人来解释原因。看来除了我之外,其他人都觉得这些回复很有用。
#create an array
a = [3, 14, 8, 2, 7, 5]

#access every other element

for i in range(0, len(a), 2):
    print a[i]

#access every other element backwards

for i in range(len(a) - 1, 0, -2):
    print a[i]

#access every odd numbered index

g = lambda x: 2*x + 1
for i in range(len(a)):
if g(i) > len(a):
        break
else:
        print a[g(i)]