Python for loop start counter initialization

一世执手 提交于 2019-12-30 06:51:18

问题


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.


回答1:


The for index in range(len(list)) loop executes the loop body with index first set to 0, then 1, then 2, etc. up to len(list) - 1. The previous value of index is ignored and overwritten. If you want index to start at iteration + 1, use the 2-argument form of range:

for index in range(iteration + 1, len(list)):



回答2:


You really should be using enumerate for 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).

for i, j in enumerate(list):
    print i, j

Your inner loop is overriding the variable index that you defined in the first loop.




回答3:


for index in range(iteration + 1, len(list))



回答4:


Try this instead:

for index in range(iteration + 1, len(l)):  # don't use "list" as a name

index is being reassigned anyway within the for-loop so index = iteration + 1 is not having any effect.



来源:https://stackoverflow.com/questions/17498407/python-for-loop-start-counter-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!