Python程式設計從入門到實踐筆記——操作列表
阿新 • • 發佈:2018-12-17
#coding=utf-8 magicians = ['alice','david','carolina'] #遍歷整個列表 for magician in magicians : print(magician) print("hello everyone!") #for迴圈(冒號和縮排) for number in range(1,6): print(number) #用range()建立數字列表 #list()、range()前閉後開 numbers = list(range(1,6)) print(numbers) #range()設定步長 even_numbers = list(range(2,21,2)) print(even_numbers) #**表示乘方 squares=[] for value in range(1,51): squares.append(value**2) print(squares) #數字列表統計 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print("min="+str(min(digits))) print("max="+str(max(digits))) print("sum="+str(sum(digits))) #列表解析 squares_1 = [value**2 for value in range(1,10)] print(squares_1) #切片 和range()範圍一樣,前閉後開 #不指定起始索引,從列表開頭開始 #不指定終止索引,終止於列表末尾 players=['jordan','james','magic','kobe','yao','bill'] print(players[0:3]) print(players[:1]) print(players[3:]) #列印最後三名運動員 print(players[-3:]) #複製列表:省略起始索引和終止索引 players_1=players[:] players.append('wade') players_1.append('paul') print(players) print(players_1) #players_1=players,players賦值給players_1,和Java中陣列賦值一樣,指向的是同一個物件,操作的是同一個物件 #元組()不可以更改其中元素的值,可以改變元組變數的值 dimensions=(100,80) print(dimensions[0]) print(dimensions[1]) dimensions=(80,80) print(dimensions[0]) print(dimensions[1])