python-循环的嵌套和用法,学习总结(升降序、冒泡)

循环嵌套
1、遍历a、b两个列表的组合

a = ['a1','a2','a3']
b = ['b1','b2','b3']
for a0 in a:
    for b0 in b:
        print('(%s,%s)'%(a0,b0))
#--------输出的结果为:-----------
(a1,b1)
(a1,b2)
(a1,b3)
(a2,b1)
(a2,b2)
(a2,b3)
(a3,b1)
(a3,b2)
(a3,b3)
#-------------------------------
#注:各位可依据该项进行九九乘法表的练习,毕竟前面文中写道,此处不再赘述

列表生成式

list_old = [100,200,300,400]
list_new = []
for old_digit in list_old:
	list_new.append(int(old_digit*0.9))
print(list_new)
#优点,代码少,一般用于比较简单的列表处理,劣势,不好调试
list_new = [old_digit for old_digit in list_old if old_digit>200]
print(list_new)

排序算法

#--------------------升降序----------------------
alist = [9,2,5,6,4]
alist.sort()#升序
# print(alist[::-1])#升序反过来显示,降序(1)

alist.sort(reverse=True)#降序(2)
print(alist)
#------------------------------------------------


#-------------------冒泡排序---------------------
#找n-1较大值,两两相邻元素对比,大往后移
alist = [9,2,5,6,4]

for i in range(0,len(alist)-1):
    for j in range(0,len(alist)-1-i):
        if alist[j] > alist[j+1]:
            alist[j],alist[j+1] = alist[j+1],alist[j]
print(alist)
#------------------------------------------------


#----------------排序更换新的列表--------------------------
#存在老列表,创建新列表,找到老列表中最小值,逐个填入新列表中
#菜鸡笔记,尝试过copy、切片倒序,但是都不符合训练理解冒泡逻辑的目的,最终内容为非备注部分
import copy
List = [3,5,7,2]#[7,5,3,2]
# List_copy = copy.copy(List)
# print('List_copy' + str(List_copy))
newList = []
i = 0
for i in range(0,(len(List)+i)):
    # print('i = ' + str(i))
    # print(List)
    for j in range(0,len(List)-1):
        if List[j] < List[j+1]:
            List[j],List[j+1] = List[j+1],List[j]
    add_digit = List.pop(len(List)-1)
    # print(add_digit)
    newList.append(add_digit)
print('newList = '+ str(newList))
# print(List[::-1])
# for add_digit in List[::-1]:
#     print(add_digit)
# newList = [add_digit for add_digit in List[::-1]]
# print(newList)

'''
List = [3,5,7,2]
newList = []
for i in range(0,len(List)):
    add_digit = min(List)
    List.remove(add_digit)
    print(add_digit)
    newList.append(add_digit)
print(newList)
'''
#------------------------------------------------------

你可能感兴趣的:(python,python,列表)