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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python에는 두 개의 목록을 연결하는 방법이 많이 있습니다. 1. 연산자 사용 간단하지만 큰 목록에서는 비효율적입니다. 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 효율적이고 읽기 쉬운 = 연산자를 사용하십시오. 4. 메모리 효율적이지만 추가 가져 오기가 필요한 itertools.chain function을 사용하십시오. 5. 우아하지만 너무 복잡 할 수있는 목록 구문 분석을 사용하십시오. 선택 방법은 코드 컨텍스트 및 요구 사항을 기반으로해야합니다.

Python 목록을 병합하는 방법에는 여러 가지가 있습니다. 1. 단순하지만 큰 목록에 대한 메모리 효율적이지 않은 연산자 사용; 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 큰 데이터 세트에 적합한 itertools.chain을 사용하십시오. 4. 사용 * 운영자, 한 줄의 코드로 중소형 목록을 병합하십시오. 5. Numpy.concatenate를 사용하십시오. 이는 고성능 요구 사항이있는 대규모 데이터 세트 및 시나리오에 적합합니다. 6. 작은 목록에 적합하지만 비효율적 인 Append Method를 사용하십시오. 메소드를 선택할 때는 목록 크기 및 응용 프로그램 시나리오를 고려해야합니다.

CompiledLanguagesOfferSpeedSecurity, while InterpretedLanguagesProvideeaseofusEandportability

Python에서, for 루프는 반복 가능한 물체를 가로 지르는 데 사용되며, 조건이 충족 될 때 반복적으로 작업을 수행하는 데 사용됩니다. 1) 루프 예제 : 목록을 가로 지르고 요소를 인쇄하십시오. 2) 루프 예제 : 올바르게 추측 할 때까지 숫자 게임을 추측하십시오. 마스터 링 사이클 원리 및 최적화 기술은 코드 효율성과 안정성을 향상시킬 수 있습니다.

목록을 문자열로 연결하려면 Python의 join () 메소드를 사용하는 것이 최선의 선택입니다. 1) join () 메소드를 사용하여 목록 요소를 ''.join (my_list)과 같은 문자열로 연결하십시오. 2) 숫자가 포함 된 목록의 경우 연결하기 전에 맵 (str, 숫자)을 문자열로 변환하십시오. 3) ','. join (f '({fruit})'forfruitinfruits와 같은 복잡한 형식에 발전기 표현식을 사용할 수 있습니다. 4) 혼합 데이터 유형을 처리 할 때 MAP (str, mixed_list)를 사용하여 모든 요소를 문자열로 변환 할 수 있도록하십시오. 5) 큰 목록의 경우 ''.join (large_li

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Dreamweaver Mac版
시각적 웹 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

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