Python uses for loop to sort elements in a list

高洛峰
Release: 2017-03-10 18:48:45
Original
6714 people have browsed it

This article introduces how Python uses a for loop to sort elements in a list

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] = temp
print list
Copy after login

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 '本次进行比较的list下标值' + 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 T 
#            print list[i],list[j]
            print '********内部的一次循环***************'
        print list 
    print  list
    print '++++++++本次内部循环结束+++++++\n\n'
Copy after login

--You can see the cycle process from the printed information--

Result:

本次进行比较的list下标值0 1
[13, 22, 6, 99, 11]
本次进行比较的list下标值0 2
********内部的一次循环***************
[6, 22, 13, 99, 11]
本次进行比较的list下标值0 3
[6, 22, 13, 99, 11]
本次进行比较的list下标值0 4
[6, 22, 13, 99, 11]
[6, 22, 13, 99, 11]
++++++++本次内部循环结束+++++++
 
 
本次进行比较的list下标值1 2
********内部的一次循环***************
[6, 13, 22, 99, 11]
本次进行比较的list下标值1 3
[6, 13, 22, 99, 11]
本次进行比较的list下标值1 4
********内部的一次循环***************
[6, 11, 22, 99, 13]
[6, 11, 22, 99, 13]
++++++++本次内部循环结束+++++++
 
 
本次进行比较的list下标值2 3
[6, 11, 22, 99, 13]
本次进行比较的list下标值2 4
********内部的一次循环***************
[6, 11, 13, 99, 22]
[6, 11, 13, 99, 22]
++++++++本次内部循环结束+++++++
 
 
本次进行比较的list下标值3 4
********内部的一次循环***************
[6, 11, 13, 22, 99]
[6, 11, 13, 22, 99]
++++++++本次内部循环结束+++++++
Copy after login


The above is the detailed content of Python uses for loop to sort elements in a list. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!