#訪問列表元素 food =['bunana','apple','orange'] print(food[0]) print(food[1]) print(food[2]) print("hello "+food[0]+"!") print("hello "+food[1]+"!") print("hello "+food[2]+"!") #修改 food =['bunana','apple','orange'] food[0]='hahaha' print(food) #增加 food =['bunana','apple','orange'] #1、末尾增加 food.append('西瓜') food.append('西紅柿') print(food) #2、在列表中插入元素 food.insert(0,"土豆") print(food) #3、刪除 #如果知道要刪除的元素在列表中的位置,可使用del 語句。 del food[0] print(food) #方法pop() 可刪除列表末尾的元素,並讓你能夠接着使用它 a=food.pop() print(food) print(a) #remove根據值刪除元素 food.remove("西瓜") print(food) #永久排序 food.sort() print(food) #反轉 food.reverse() print(food) #長度 print(len(food)) #遍歷 #創建一個列表,其中包含前10個整數(即1~10)的平方 a=[] for i in range(1,11): a.append(i**2) print(a) # 對數字列表執行簡單的統計計算 b=max(a) b1=min(a) b2=sum(a) print(b,b1,b2) #使用一個for 循環打印數字1~20(含)。 for a in range (1,21): print(a) #創建一個列表,其中包含數字1~1 000 000,再使用一個for 循環將這些數字打印出來,求最大、最小、總和 c=[] for a in range (1,1000001): c.append(a) print(max(c)) print(min(c)) print(sum(c)) #6 奇數 :通過給函數range() 指定第三個參數來創建一個列表,其中包含1~20的奇數;再使用一個for 循環將這些數字都打印出來 d=[] for i in range (1,21): if i%2 != 0: print(i) d.append(i) print(d) #用3的倍數 :創建一個列表,其中包含3~30內能被3整除的數字;再使用一個for 循環將這個列表中的數字都打印出來。 e=[] for i in range (3,31,3): print(i) e.append(i) print(e) #立方 :將同一個數字乘三次稱為立方。例如,在Python中,2的立方用2**3 表示。請創建一個列表,其中包含前10個整數(即1~10)的立方,再使用一個for 循 #環將這些立方數都打印出來。 f =[] for i in range (1,11): v=i**3 print(v) f.append(v) print(f) #立方解析 :使用列表解析生成一個列表,其中包含前10個整數的立方 g=[i**3 for i in range(1,11)] print(g) #切片 g=[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] #前3個、前5個、3個開始到結束、后三個、復制列表 print(g[0:3]) print(g[:5]) print(g[3:]) print(g[-3:]) print(g[:]) #遍歷切片 name=["laoli","laosong","laozhang"] for i in name[1:3]: print(i) #列表的練習 #嘉賓名單 :如果你可以邀請任何人一起共進晚餐(無論是在世的還是故去的),你會邀請哪些人?請創建一個列表, # 其中包含至少3個你想邀請的人;然后,使用 #這個列表打印消息,邀請這些人來與你共進晚餐。 mingdan=['laosong','laosun','laozheng'] for a in mingdan: print("hello "+a +", welcome to eat today night!") #laozheng有事沒法來 print(mingdan[2]+" you shi mei fa lai eat!") mingdan[2]='laorui' for a in mingdan: print("hello "+a +", welcome to eat today night!") #找到了一個更大的餐桌mingdan1 print("have a geng big can zhuo") #在邀請3個 mingdan.append("xiaozheng") mingdan.insert(0,"xiaosong") mingdan.insert(2,"xiaosun") print(mingdan) for a in mingdan: print("hello "+a +", welcome to eat today night!") #縮減名單 :剛得知新購買的餐桌無法及時送達,因此只能邀請兩位嘉賓。 print("sorry,zhi you two people can come !") print(len(mingdan)) #每刪除一個,通知一個 print("sorry "+mingdan[5]+" you can't come !") mingdan.pop() print("sorry "+mingdan[4]+" you can't come !") mingdan.pop() print("sorry "+mingdan[3]+" you can't come !") mingdan.pop() print("sorry "+mingdan[2]+" you can't come !") mingdan.pop() print(mingdan) #通知剩下的可以來 for a in mingdan: print("hello "+a +", welcome to eat today night!") #吃完了刪除 del mingdan[0] print(mingdan) del mingdan[0] print(mingdan) print("eat end !")