標籤:結果 with pts bsp 個數 取值 class code 語句
排序:
1:整理順序
#冒泡lista = [5,7,11,19,99,63,3,9,1]list = []while lista != []: number = 0 for i in lista: if number < i: number = i lista.remove(number) list.append(number)print(list)
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[99, 63, 19, 11, 9, 7, 5, 3, 1]Process finished with exit code 0
#選擇lista = [5,7,11,19,99,63,3,9,1]list = []while lista != []: for i in lista: number = 1 for j in lista: if number < j: number = j lista.remove(number) list.append(number)print(list)
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[99, 63, 19, 11, 9, 7, 5, 3, 1]Process finished with exit code 0
2:sort()函數
#sort函數lista =[5,7,11,19,99,63,3,9,1]lista.sort()print(lista)
列印結果:
D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[1, 3, 5, 7, 9, 11, 19, 63, 99]Process finished with exit code 0
3:加上一個數
#若a=18,在原來的list中按順序加上這個個數list = [1,4,7,9,11,14,19,34,60,79,98]print("前:%s" %list)a = 18list.append(a)list_1 = []while list != []: number = 100 for i in list: if i < number: number = i list.remove(number) list_1.append(number)print("後:%s" %list_1)
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py前:[1, 4, 7, 9, 11, 14, 19, 34, 60, 79, 98]後:[1, 4, 7, 9, 11, 14, 18, 19, 34, 60, 79, 98]Process finished with exit code 0
執行個體:
3*3表
#3*3表listx = [1,2,3,]for i in listx: for j in listx: if i >= j: x = i*j print("%s*%s=%s" %(i,j,x) ,end=" ") print()
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 Process finished with exit code 0
列表反向列印:list_num = ["1","2","3"]列印順序:3,2,1
使用len()函數
#反向列表(len() 方法返回對象(字元、列表、元組等)長度或項目個數)list_num = ["1","2","3"]i = len(list_num)print(list_num[i-1::-1])
列印結果:
D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[‘3‘, ‘2‘, ‘1‘]Process finished with exit code 0
使用reverse()函數
list_num = ["1","2","3"]list_num.reverse()print(list_num)
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[‘3‘, ‘2‘, ‘1‘]Process finished with exit code 0
使用for語句
a = [1,2,3,4,5,6]num = len(a)for i in range(int(num/2)): a[i],a[num -i -1 ] = a[num-i-1],a[i]print(a)
D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py[6, 5, 4, 3, 2, 1]Process finished with exit code 0
小知識:
list_num = ["1","2","3"]for i in list_num[::-1]:#從後往前取值 print(i)
列印結果:D:\untitled\1\venv\Scripts\python.exe D:/untitled/1/venv/main.py321Process finished with exit code 0
python:數組/列表(remove()函數、append()函數、sort()函數、reverse()函數)