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

PCEP 認證準備的 Python 元組和列表提示

Sep 29, 2024 am 06:12 AM

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

Java教學
1662
14
CakePHP 教程
1419
52
Laravel 教程
1311
25
PHP教程
1261
29
C# 教程
1234
24
Python vs.C:申請和用例 Python vs.C:申請和用例 Apr 12, 2025 am 12:01 AM

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

Python:遊戲,Guis等 Python:遊戲,Guis等 Apr 13, 2025 am 12:14 AM

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

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

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

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

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

Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python和時間:充分利用您的學習時間 Python和時間:充分利用您的學習時間 Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

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

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

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

See all articles