Python Looping Modify list considerations
Python loop list and need to modify the list elements, you should be careful not to loop the list, side modify the list, otherwise it will lead to strange and wonderful results error.
An example of a sort with a simple bubbling sort
List [12, 3, 15, 7, 45, 33, 9, 76, 40, 56] using the bubbling algorithm in order from small to large. (write only once for the sorting process, that is, to find the largest put to the last)
If written as:
Src_list = [3, 7, 9, $, 56]for (index, value) in enumerate (Src_list[:-1]): #最后一个元素不用循环if value ; Src_list[index+1]:tmp = Valuesrc_list[index] = src_list[index+1]src_list[index+1] = Tmpprint (src_list)
The following is the result of running the code above:
[3, 12, 7, 15, 33, 9, 33, 40, 76, 56]
You can see that element 33 becomes two times and element 45 is gone.
The correct way to do this is to replace the loop list with a different method, and only modify the list. Such as:
Src_list = [3], 7, 9, 1, 56]for index in xrange (Len (src_list)-+ +): #最后一个元素不用循环 if Src_list[index] > Src_list[index+1]:tmp = Src_list[index]src_list[index] = src_list[index+1]src_list[index+1] = Tmpprint (src_list)
By looping through an iterator instead of a loop list, you can access the list element in order, and then modify the list element so that it doesn't go wrong! 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0057.gif "alt=" J_0057.gif "/>
Python Looping Modify list considerations