Python for 循环启动计数器初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17498407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python for loop start counter initialization
提问by user2555288
for iteration in range(len(list) - 1):
index = iteration +1 #This is the line which has no effect on the inner loop
for index in range(len(list)):
if list[iteration] > list[index]:
newmin = list[index]
newminindex = index
if iteration != newminindex :
swapnumbers(list,iteration, newminindex)
The above is a code snippet I wrote for selection sort algorithm. However I see the inner loop start counter always starting from 0. Request for expert comment.
以上是我为选择排序算法编写的代码片段。但是我看到内循环开始计数器总是从 0 开始。请求专家评论。
回答by bojangler
for index in range(iteration + 1, len(list))
回答by arshajii
Try this instead:
试试这个:
for index in range(iteration + 1, len(l)): # don't use "list" as a name
indexis being reassigned anyway within the for-loop so index = iteration + 1is not having any effect.
index无论如何都在for-loop 中被重新分配,因此index = iteration + 1没有任何影响。
回答by user2357112 supports Monica
The for index in range(len(list))loop executes the loop body with indexfirst set to 0, then 1, then 2, etc. up to len(list) - 1. The previous value of indexis ignored and overwritten. If you want indexto start at iteration + 1, use the 2-argument form of range:
该for index in range(len(list))循环执行循环体与index第一组到0,然后1,再2等,至多len(list) - 1。的先前值将index被忽略并覆盖。如果要从index开始iteration + 1,请使用 的 2 参数形式range:
for index in range(iteration + 1, len(list)):
回答by TerryA
You really should be using enumeratefor stuff like this, as you can loop through the index and the value at the same time (which will save you the hassle of using two for-loops).
你真的应该使用enumeratefor 这样的东西,因为你可以同时循环遍历索引和值(这样可以省去使用两个 for 循环的麻烦)。
for i, j in enumerate(list):
print i, j
Your inner loop is overriding the variable indexthat you defined in the first loop.
您的内部循环覆盖了index您在第一个循环中定义的变量。

