This article introduces how to sort elements in a list using a for loop. This article introduces how to sort elements in a list using a for loop.
list = [13, 22, 6, 99, 11]for m in range(len(list)-1): for n in range(m+1, len(list)): if list[m]> list[n]: temp = list[n] list[n] = list[m] list[m] = tempprint list
Result:
[6, 11, 13, 22, 99]
Analysis:
List = [13, 22, 6, 99, 11] for I in range (len (list)-1): for j in range (I + 1, len (list )): # print str (I) # print "init --" + str (j) print 'values of the list below this comparison '+ str (I), str (j) if list [I]> list [j]: # print I, j # print '-----' + str (list [I]) + str (list [j]) + '-------' T = list [j] list [j] = list [I] list [I] = T # print list [I], list [j] print '********* an internal loop **************** 'print list print listprint' +++ ++ the end of this internal cycle +++ ++ \ n \ n'
-- The circular process can be seen from the printed information --
Result:
The value of the list below this comparison is 0 1 [13, 22, 6, 99, 11] The value of the list under this comparison is 0 2 *, 22, 13, 99, 11] The value of the list under this comparison is 0 3 [6, 22, 13, 99, 11] The value of the list under this comparison is 0 4 [6, 22, 13, 99, 11] [6, 22, 13, 99, 11] ++ this internal cycle ends with ++ this comparison list under the standard value of 1 2 ********* internal, 13, 22, 99, 11] values under the list compared this time: 1 3 [6, 13, 22, 99, 11] In this comparison, the value of the list is 1 4 *, 11, 22, 99, 13] [6, 11, 22, 99, 13] ++ this internal cycle ends with ++ the list of marked values 2 3 [6, 11, 22, 99, 13] a loop inside the list marked as 2 4*6, 11, 13, 99, 22] [6, 11, 13, 99, 22] ++ this internal cycle ends with ++ this comparison list under the standard value of 3 4 ********* internal, 11, 13, 22, 99] [6, 11, 13, 22, 99] ++ the internal cycle ends.
The above is the details about how Python uses the for loop to sort the elements in the list. for more information, see other related articles in the first PHP community!