Vas*_*lis 1 python indexing for-loop
是否可以在Python for循环中操作索引指针?
例如在PHP中,将打印以下示例1 3:
$test = array(1,2,3,4);
for ($i=0; $i < sizeof($test); $i++){
print $test[$i].' ';
$i++;
}
Run Code Online (Sandbox Code Playgroud)
但是在Python中,当我尝试增加索引时没有任何效果.例如,以下将打印所有数字:
test = ['1', '2', '3', '4']
for i in xrange(len(test)):
print test[i]
i=i+1
Run Code Online (Sandbox Code Playgroud)
有没有办法在循环内操作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
Run Code Online (Sandbox Code Playgroud)
当你试图操纵索引时,i你正在做它,但是当for循环进入下一个迭代时,它会分配给i下一个值,xrange(len(test))这样它就不会受到你所做的操作的影响.
你可能想尝试一下while:
test = ['1', '2', '3', '4']
i = 0
while i < 4:
print test[i]
i += 2
Run Code Online (Sandbox Code Playgroud)