Petua Python Tuple dan Senarai untuk Persediaan Pensijilan PCEP

DDD
Lepaskan: 2024-09-29 06:12:02
asal
880 orang telah melayarinya

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]
Salin selepas log masuk

튜플 예:

# 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
Salin selepas log masuk

2. 목록과 튜플의 구문을 숙지하세요
리스트는 대괄호 [ ]로 표시되고, 튜플은 괄호( )로 묶입니다. 목록이나 튜플을 만드는 것은 적절한 구문을 사용하여 변수에 값을 선언하는 것만큼 간단합니다. 초기화 후에는 튜플을 수정할 수 없으므로 올바른 구문을 사용하는 것이 중요합니다.

목록 예:

# creating a list of fruits
fruits = ["apple", "banana", "orange"]
Salin selepas log masuk

튜플 예:

# creating a tuple of colors
colors = ("red", "green", "blue")
Salin selepas log masuk

3. 항목 추가 및 제거 방법 알아보기
목록에는 추가(), 확장() 및 제거()와 같은 항목을 추가하고 제거하기 위한 다양한 내장 메서드가 있습니다. 반면에 튜플에는 내장된 메소드 수가 적고 항목을 추가하거나 제거하는 메소드가 없습니다. 따라서 튜플을 수정해야 하는 경우 기존 튜플을 변경하는 대신 새 튜플을 생성해야 합니다.

목록 예:

# 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"]
Salin selepas log masuk

튜플 예:

# 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
Salin selepas log masuk

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
Salin selepas log masuk

보시다시피 튜플을 반복하는 것이 목록을 반복하는 것보다 약간 빠릅니다.

5. 목록과 튜플의 적절한 사용 사례 이해
목록은 쉽게 수정할 수 있으므로 시간이 지남에 따라 변경될 수 있는 항목 컬렉션을 저장하는 데 적합합니다. 대조적으로, 튜플은 변경되지 않고 유지되어야 하는 항목의 지속적인 컬렉션에 이상적입니다. 예를 들어, 변경될 수 있는 식료품 목록에는 목록이 적합할 수 있지만 요일은 동일하게 유지되므로 튜플이 요일을 저장하는 데 더 적합합니다.

목록 예:

# creating a list of groceries
grocery_list = ["milk", "bread", "eggs", "chicken"]
# adding a new item to the grocery list
grocery_list.append("bananas")
Salin selepas log masuk

튜플 예:

# 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
Salin selepas log masuk

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
Salin selepas log masuk

튜플은 리스트에 비해 메모리를 덜 소모하는 것을 볼 수 있습니다.

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
Salin selepas log masuk

튜플 예:

# 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
Salin selepas log masuk

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
Salin selepas log masuk

튜플 예:

# 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
Salin selepas log masuk

목록과 튜플의 차이점, 적절한 사용 사례, 구문을 이해하면 PCEP 시험을 잘 준비할 수 있습니다. 지식을 확고히 하고 시험 합격 가능성을 높이려면 다양한 시나리오에서 이러한 데이터 구조를 사용하여 연습하는 것을 잊지 마십시오. 연습을 하면 완벽해진다는 점을 명심하세요!

Atas ialah kandungan terperinci Petua Python Tuple dan Senarai untuk Persediaan Pensijilan PCEP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!