文章目錄
- 一. 遍歷整個列表
- 1. 在for循環中執行更多操作
- 2. 在for循環結束后執行一些操作
- 二. 避免縮進錯誤
- 三. 創建數值列表
- 1. 使用函數range()
- 2. 使用range()創建數字列表
- 3. 指定步長。
- 4. 對數字列表執行簡單的統計計算
- 5. 列表解析
- 五. 使用列表的一部分-切片
- 1. 切片
- 2. 遍歷切片
- 3. 復制列表(淺拷貝與深拷貝)
- 4. 元組
一. 遍歷整個列表
if __name__ == '__main__':magicians = ['alice', 'david', 'carolina']for magician in magicians:print(magician)
?
1. 在for循環中執行更多操作
if __name__ == '__main__':magicians = ['alice', 'david', 'carolina']for magician in magicians:print(f"{magician.title()}, that was a great trick")
?
2. 在for循環結束后執行一些操作
在for循環后面,沒有縮進的代碼都只執行一次,不會重復執行。
if __name__ == '__main__':magicians = ['alice', 'david', 'carolina']for magician in magicians:print(f"{magician.title()}, that was a great trick")print("Thank you。")
?
二. 避免縮進錯誤
Python根據縮進來判斷代碼行與前一個代碼行的關系。
簡單地說,它要求你使用縮進讓代碼整潔而結構清晰。在較長的Python程序中,你將看到縮進程度各不相同的代碼塊,從而對程序的組織結構有大致的認識。
下面來看一些較為常見的縮進錯誤。
忘記縮進
對于位于for語句后面且屬于循環組成部分的代碼行,一定要縮進。
忘記縮進額外的代碼行:
magicians = ['alice', 'david', 'carolina']for magician in magicians:print(f"{magician.title()}, that was a great trick!")print(f"I can't wait to see your next trick, {magician.title()}.\n") # 也需要進行縮進
?
不必要的縮進
函數調用print()(見?)無須縮進,因為它并非循環的組成部分。
message = "Hello Python world!"
? print(message)
?
遺漏了冒號
for語句末尾的冒號告訴Python,下一行是循環的第一行。
magicians = ['alice', 'david', 'carolina']
? for magician in magiciansprint(magician)
如果不小心遺漏了冒號,如?所示,將導致語法錯誤,因為Python不知道你意欲何為。
?
三. 創建數值列表
1. 使用函數range()
for value in range(1, 5):print(value)
它不會打印5,只有1到4。
?
2. 使用range()創建數字列表
要創建數字列表,可使用函數list()將range()的結果直接轉換為列表。
numbers = list(range(1, 6))
print(numbers)
?
3. 指定步長。
為此,可給這個函數指定第三個參數,看一個例子:
打印1~10的偶數:
even_numbers = list(range(2, 11, 2))
print(even_numbers)
?
創建一個列表,其中包含前10個整數(1~10)的平方
squares = []for value in range(1,11):
? squares.append(value**2)print(squares)
?
4. 對數字列表執行簡單的統計計算
最小、最大、總和。
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
本節使用的數字列表都很短,但這里介紹的知識也適用于包含數百萬個數的列表。
?
5. 列表解析
列表解析將for循環和創建新元素的代碼合并成一行,并自動附加新元素
squares = [value**2 for value in range(1, 11)]
print(squares)
?
五. 使用列表的一部分-切片
處理列表的部分元素,Python稱之為切片。
1. 切片
要創建切片,可指定要使用的第一個元素和最后一個元素的索引。與函數range()一樣,Python在到達第二個索引之前的元素后停止。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
? print(players[0:3])# ['charles', 'martina', 'michael']
如果沒有指定第一個索引,Python將自動從列表開頭開始:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
如果要提取從第三個元素到列表末尾的所有元素,可將起始索引指定為2,并省略終止索引:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
如果要輸出名單上的最后三名隊員,可使用切片players[-3:]:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
?
2. 遍歷切片
遍歷前三名隊員,并打印他們的名字:
players = ['charles', 'martina', 'michael', 'florence', 'eli']print("Here are the first three players on my team:")
? for player in players[:3]:print(player.title())
?
3. 復制列表(淺拷貝與深拷貝)
要復制列表,可創建一個包含整個列表的切片,方法是同時省略起始索引和終止索引([:])。
? my_foods = ['pizza', 'falafel', 'carrot cake']
? friend_foods = my_foods[:]print("My favorite foods are:")print(my_foods)print("\nMy friend's favorite foods are:")print(friend_foods)
如果只是將my_foods賦給friend_foods,就不能得到兩個列表。
my_foods = ['pizza', 'falafel', 'carrot cake']# 這行不通:
? friend_foods = my_foodsmy_foods.append('cannoli')friend_foods.append('ice cream')print("My favorite foods are:")print(my_foods)print("\nMy friend's favorite foods are:")print(friend_foods)# My favorite foods are:
# ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']# My friend's favorite foods are:
# ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
這種語法實際上是讓Python將新變量friend_foods關聯到已與my_foods相關聯的列表,因此這兩個變量指向同一個列表。類似于淺拷貝。
?
4. 元組
Python將不能修改的值稱為不可變的,而不可變的列表被稱為元組。
定義元組
元組看起來很像列表,但使用圓括號而非中括號來標識。
定義元組后,就可使用索引來訪問其元素,就像訪問列表元素一樣。
? dimensions = (200, 50)
? print(dimensions[0])print(dimensions[1])
dimensions = (200, 50)
for dimension in dimensions:print(dimension)
雖然不能修改元組的元素,但可以給存儲元組的變量賦值。因此,如果要修改前述矩形的尺寸,可重新定義整個元組:
? dimensions = (200, 50)print("Original dimensions:")for dimension in dimensions:print(dimension)? dimensions = (400, 100)
? print("\nModified dimensions:")for dimension in dimensions:print(dimension)
如果需要存儲的一組值在程序的整個生命周期內都不變,就可以使用元組。
?
參考:《Python編程:從入門到實踐(第二版)》