搜尋
首頁後端開發Python教學PCEP 認證準備的 Python 元組和列表提示

Python Tuples and Lists Tips for PCEP Certification Preparation

立志成為 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:遊戲,Guis等Python:遊戲,Guis等Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python vs.C:申請和用例Python vs.C:申請和用例Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時的Python計劃:一種現實的方法2小時的Python計劃:一種現實的方法Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python:探索其主要應用程序Python:探索其主要應用程序Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

您可以在2小時內學到多少python?您可以在2小時內學到多少python?Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?Apr 02, 2025 am 07:18 AM

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Apr 02, 2025 am 07:12 AM

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。