立志成為 Python 認證入門級程式設計師 (PCEP) 需要徹底了解 Python 中的基本資料結構,例如清單和元組。
清單和元組都能夠在 Python 中儲存對象,但這兩種資料結構在用法和語法上存在關鍵差異。為了幫助您在 PCEP 認證考試中取得好成績,這裡有一些掌握這些資料結構的基本技巧。
1。了解清單和元組的差異
Python 中的列表是可變的,這意味著它們可以在創建後進行修改。另一方面,元組是不可變的,這意味著它們一旦創建就無法更改。這意味著元組的記憶體需求較低,並且在某些情況下比列表更快,但它們提供的靈活性較低。
列表範例:
# creating a list of numbers numbers = [1, 2, 3, 4, 5] # modifying the list by changing the fourth element numbers[3] = 10 print(numbers) # output: [1, 2, 3, 10, 5]
元組範例:
# creating a tuple of colors colors = ("red", "green", "blue") # trying to modify the tuple by changing the second element colors[1] = "yellow" # this will result in an error as tuples are immutable
2。熟悉列表和元組的語法
列表以方括號 [ ] 表示,而元組則用括號 ( ) 括起來。建立清單或元組就像使用適當的語法向變數宣告值一樣簡單。請記住,元組在初始化後無法修改,因此使用正確的語法至關重要。
列表範例:
# creating a list of fruits fruits = ["apple", "banana", "orange"]
元組範例:
# creating a tuple of colors colors = ("red", "green", "blue")
3。了解如何新增和刪除項目
清單有各種用於新增和刪除項目的內建方法,例如append()、extend() 和remove()。另一方面,元組的內建方法較少,且沒有任何新增或刪除項目的方法。因此,如果您需要修改元組,則必須建立一個新元組,而不是更改現有元組。
列表範例:
# adding a new fruit to the end of the list fruits.append("mango") print(fruits) # output: ["apple", "banana", "orange", "mango"] # removing a fruit from the list fruits.remove("banana") print(fruits) # output: ["apple", "orange", "mango"]
元組範例:
# trying to add a fruit to the end of the tuple fruits.append("mango") # this will result in an error as tuples are immutable # trying to remove a fruit from the tuple fruits.remove("banana") # this will also result in an error
4。了解性能差異
由於其不變性,元組通常比列表更快。留意需要儲存固定項目集合的場景,並考慮使用元組而不是清單來提高效能。
您可以使用Python中的timeit模組測試清單和元組之間的效能差異。以下是一個比較迭代列表和包含 10 個元素的元組所需時間的範例:
# importing the timeit module import timeit # creating a list and a tuple with 10 elements numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # testing the time it takes to iterate through the list list_time = timeit.timeit('for num in numbers_list: pass', globals=globals(), number=100000) print("Time taken for list: ", list_time) # output: Time taken for list: 0.01176179499915356 seconds # testing the time it takes to iterate through the tuple tuple_time = timeit.timeit('for num in numbers_tuple: pass', globals=globals(), number=100000) print("Time taken for tuple: ", tuple_time) # output: Time taken for tuple: 0.006707087000323646 seconds
如您所見,迭代元組比迭代列表稍快。
5。了解清單和元組的適當用例
清單適合儲存可能隨時間變化的項目集合,因為它們可以輕鬆修改。相較之下,元組非常適合需要保持不變的項目的恆定集合。例如,雖然清單可能適合可以更改的雜貨清單,但元組更適合存放一周中的幾天,因為它們保持不變。
列表範例:
# creating a list of groceries grocery_list = ["milk", "bread", "eggs", "chicken"] # adding a new item to the grocery list grocery_list.append("bananas")
元組範例:
# creating a tuple of weekdays weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") # trying to add a new day to the tuple weekdays.append("Saturday") # this will result in an error as tuples cannot be modified after creation
6。注意記憶體使用
由於其靈活性,列表比元組消耗更多的內存,而元組由於其不變性而佔用更少的空間。在處理大型資料集或記憶體密集型應用程式時,這一點尤其重要。
可以使用Python中的sys模組來檢查變數的記憶體使用量。以下是比較列表和具有一百萬個元素的元組的記憶體使用情況的範例:
# importing the sys module import sys # creating a list with one million elements numbers_list = list(range(1000000)) # checking the memory usage of the list list_memory = sys.getsizeof(numbers_list) print("Memory usage for list: ", list_memory) # output: Memory usage for list: 9000112 bytes # creating a tuple with one million elements numbers_tuple = tuple(range(1000000)) # checking the memory usage of the tuple tuple_memory = sys.getsizeof(numbers_tuple) print("Memory usage for tuple: ", tuple_memory) # output: Memory usage for tuple: 4000072 bytes
您可以看到,與清單相比,元組消耗的記憶體較少。
7。知道如何迭代列表和元組
列表和元組都可以透過使用循環進行迭代,但由於它們的不變性,元組可能會稍微快一些。另請注意,列表可以儲存任何類型的數據,而元組只能包含可哈希元素。這意味著元組可以用作字典鍵,而列表則不能。
列表範例:
# creating a list of numbers numbers = [1, 2, 3, 4, 5] # iterating through the list and checking if a number is present for num in numbers: if num == 3: print("Number 3 is present in the list") # output: Number 3 is present in the list
元組範例:
# creating a tuple of colors colors = ("red", "green", "blue") # iterating through the tuple and checking if a color is present for color in colors: if color == "yellow": print("Yellow is one of the colors in the tuple") # this will not print anything as yellow is not present in the tuple
8。熟悉內建函數與操作
雖然與元組相比,列表具有更多的內建方法,但這兩種資料結構都具有一系列您應該熟悉 PCEP 考試的內建函數和運算符。其中包括 len()、max() 和 min() 等函數,以及 in 和 not in 等運算符,用於檢查某個項目是否在清單或元組中。
列表範例:
# creating a list of even numbers numbers = [2, 4, 6, 8, 10] # using the len() function to get the length of the list print("Length of the list: ", len(numbers)) # output: Length of the list: 5 # using the in and not in operators to check if a number is present in the list print(12 in numbers) # output: False print(5 not in numbers) # output: True
元組範例:
# creating a tuple of colors colors = ("red", "green", "blue") # using the max() function to get the maximum element in the tuple print("Maximum color: ", max(colors)) # output: Maximum color: red # using the in and not in operators to check if a color is present in the tuple print("yellow" in colors) # output: False print("green" not in colors) # output: False
透過了解清單和元組的差異、適當的用例以及語法,您將為 PCEP 考試做好充分準備。請記住在不同場景中練習使用這些資料結構,以鞏固您的知識並增加通過考試的機會。請記住,熟能生巧!
以上是PCEP 認證準備的 Python 元組和列表提示的詳細內容。更多資訊請關注PHP中文網其他相關文章!