백엔드 개발 파이썬 튜토리얼 PCEP 인증 준비를 위한 Python 튜플 및 목록 팁

PCEP 인증 준비를 위한 Python 튜플 및 목록 팁

Sep 29, 2024 am 06:12 AM

Python Tuples and Lists Tips for PCEP Certification Preparation

Python 認定エントリーレベル プログラマー (PCEP) を目指すには、リストやタプルなど、Python の基本的なデータ構造を完全に理解する必要があります。

リストとタプルはどちらも Python でオブジェクトを保存できますが、これら 2 つのデータ構造には使用法と構文に大きな違いがあります。 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 モジュールを使用して、変数のメモリ使用量を確認できます。以下は、リストと 100 万個の要素を持つタプルのメモリ使用量を比較する例です:

# 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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? 한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? Apr 01, 2025 pm 11:15 PM

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? 10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? Apr 02, 2025 am 07:18 AM

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Apr 01, 2025 pm 10:51 PM

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

문자열을 통해 객체를 동적으로 생성하고 방법을 파이썬으로 호출하는 방법은 무엇입니까? 문자열을 통해 객체를 동적으로 생성하고 방법을 파이썬으로 호출하는 방법은 무엇입니까? Apr 01, 2025 pm 11:18 PM

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? 중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? Apr 02, 2025 am 07:15 AM

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

인기있는 파이썬 라이브러리와 그 용도는 무엇입니까? 인기있는 파이썬 라이브러리와 그 용도는 무엇입니까? Mar 21, 2025 pm 06:46 PM

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

See all articles