二、列表

鹤比纷恆红發表於2024-07-03

2.1 列表是什麼

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
結果:['trek','cannondale','redline','specialized']

① 訪問列表元素

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0]) #0-3
print(bicycles[3].title())
結果:trek  Specialized

這裡可以將索引指定為-1,可讓Python返回最後一個列表元素,依此類推。

② 使用列表中的各個值

任務:列印這句話My first bicycle was a Trek.

bicycles = ['trek','cannondale','redline','specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
結果:My first bicycle was a Trek.

2.2 修改、新增和刪除元素

① 修改列表元素

指定列表名和要修改的元素的索引,再指定該元素的新值。

bicycles[0]='ducati'

② 在列表中新增元素

bicycles.append('honda')(append:在列表末尾插入元素)

bicycles.insert(0,'ducati')(insert:在列表指定位置插入元素)

③ 在列表中刪除元素

del bicycles[0](del:刪除列表指定位置元素)

motorcycles = ["honda","yamaha","suzuki"]
print(motorcycles)
    
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
    結果["honda","yamaha","suzuki"]
        ["honda","yamaha"]
        suzuki

(pop:刪除列表元素並彈出,預設刪除最後一個元素)

motorcycles.remover('ducati')(remove:根據值來刪除元素)

2.3 組織列表

① 使用方法sort()對列表永久排序

cars = ["bmw","audi","toyota","subaru"]
cars.sort()#按字母順序排序
cars.sort(reverse=True)#按字母順序相反的順序排序

② 使用函式sorted()對列表臨時排序

cars = ["bmw","audi","toyota","subaru"]
pirnt("\nHere is the sorted list:")
print(sorted(cars))
pirnt(cars)
    結果:Here is the sorted list:
          [audi,bmw,subau,toyota]#按字母順序排序
          [bmw,audi,toyota,subaru]

③ 使用reverse()翻轉列表元素的排列順序

cars.reverse()#永久修改

④ 確定列表長度-len()

len(cars) #4

2.4 操作列表

① 遍歷整個列表-for

magicians = ["alice","david","carolina"]
for magician in magicians:  #注意冒號必不可少
    print(magician)
    #每次迴圈將陣列中的值賦值於magician,然後輸出magician,直到迴圈玩陣列中所有制
    
    print(f"{magician.title()},that was a great trick!")
    pirnt(f"I can't wait to see your next trick,{magician.title()}.\n")
    
alice
david
carolina

Alice,that was a great trick!
I can't wait to see your next trick,Alice.

David,that was a great trick!
I can't wait to see your next trick,David.

Carolina,that was a great trick!
I can't wait to see your next trick,Carolina.

② 建立數值列表-list(),range()

range(x)= range(0,x)
range(x,y)
range(x,y,z)

list(range(6))   #[0,1,2,3,4,5]
list(range(1,6)  #[1,2,3,4,5],注意是1-5
list(range(1,6,1))  #[1,2,3,4,5],步長為1
     
任務:建立一個列表,包含1-10的平方。
squares = []
for value in range(1,11):
     square = value**2
     squares.append(square)  #兩句可合併為squares.append(value**2)
     #以上程式碼可合併為squares = [value ** 2 for value in range(1,11)]
print(squares)

③ 對數字列表執行簡單的統計計算

digits = [1,2,4,5,6,7]
max(digits) #最大值
min(digits) #最小值
sum(digits) #總和

④ 使用列表的一部分

切片:
players = ['charles','martina','michael','florence','eli']
#列印列表全部元素
print(players[:])
#列印列表的第一個元素(索引0)
print(plaers[0])
#列印列表的第1、2、3個元素(索引0,1,2)
print(players[0:3])
print(players[:3])
#列印列表的第3、4、5個元素(索引2,3,4)
print(players[2:5])
print(players[2:])
#列印列表的最後三個元素(負數索引)
print(players[-3:])
#每隔1個元素就提取1個
print(players[0:4])
print(players[0:4:1])
#每隔2個元素就提取1個
print(plaers[0:4:2])

遍歷切片
players = ['charles','martina','michael','florence','eli']
for player in players[0:3]:
    print(player.title())

複製列表:

my_foods=['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
#若這裡直接friend_foods = my_foods複製列表的話,後續對其新增值處理,兩個列表輸出的值仍還是相同的
my_foods.append('cannoli')
friend_foods.append('ice crean')

print("My favorite foods are:")
print(my_foods)

print("\nMy Friend's Favorite Foods are:")
print(friend_foods)

2.5 元組--不可變的列表(小括號)

例:dimension = (269,40)

① 遍歷元組中的所有值

dimensions = (200,50)
for dimension in dimensions:
    print(dimension)

200
50

② 修改元組變數

不用透過索引賦值的方式來修改元組變數

dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
    pirnt(dimension)
    
dimensions = (200,50)
print("\nModified dimensions:")
for dimension in dimensions:
    pirnt(dimension)
    
Original dimensions:
200
50

Modified dimensions:
400
100

相關文章