ホームページ バックエンド開発 Python チュートリアル Python のタプルとリスト PCEP 認定準備のヒント

Python のタプルとリスト PCEP 認定準備のヒント

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 考試做好充分準備。請記住在不同場景中練習使用這些資料結構,以鞏固您的知識並增加通過考試的機會。請記住,熟能生巧!

以上がPython のタプルとリスト PCEP 認定準備のヒントの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

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:ゲーム、GUIなど Python:ゲーム、GUIなど Apr 13, 2025 am 12:14 AM

PythonはゲームとGUI開発に優れています。 1)ゲーム開発は、2Dゲームの作成に適した図面、オーディオ、その他の機能を提供し、Pygameを使用します。 2)GUI開発は、TKINTERまたはPYQTを選択できます。 TKINTERはシンプルで使いやすく、PYQTは豊富な機能を備えており、専門能力開発に適しています。

Python vs. C:曲線と使いやすさの学習 Python vs. 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、時間、およびスケジュールモジュールを使用できます。 1. DateTimeモジュールは、学習時間を記録および計画するために使用されます。 2。時間モジュールは、勉強と休息の時間を設定するのに役立ちます。 3.スケジュールモジュールは、毎週の学習タスクを自動的に配置します。

Python vs. C:パフォーマンスと効率の探索 Python vs. C:パフォーマンスと効率の探索 Apr 18, 2025 am 12:20 AM

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

Python:自動化、スクリプト、およびタスク管理 Python:自動化、スクリプト、およびタスク管理 Apr 16, 2025 am 12:14 AM

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか? Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか? Apr 27, 2025 am 12:03 AM

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

See all articles