Lists และ Tuples
Lists — ลำดับที่เปลี่ยนแปลงได้
หัวข้อที่มีชื่อว่า “Lists — ลำดับที่เปลี่ยนแปลงได้”list คือ container หลักของ Python ที่เก็บลำดับของ object ใด ๆ และรองรับการเปลี่ยนแปลงค่าภายใน
fruits = ['apple', 'banana', 'cherry']fruits.append('date') # เพิ่มที่ท้ายfruits.insert(1, 'avocado') # แทรกก่อน index 1fruits.remove('banana') # ลบรายการแรกที่พบprint(fruits) # ['apple', 'avocado', 'cherry', 'date']Method ที่ใช้บ่อย
หัวข้อที่มีชื่อว่า “Method ที่ใช้บ่อย”| Method | คำอธิบาย |
|---|---|
append(x) | เพิ่ม x ที่ท้าย |
insert(i, x) | แทรก x ก่อน index i |
remove(x) | ลบรายการแรกที่ตรงกับ x |
pop(i=-1) | ลบและคืนค่า item ที่ index i |
sort(key=None, reverse=False) | เรียงลำดับใน place |
reverse() | กลับลำดับใน place |
index(x) | คืน index ของรายการแรกที่ตรงกับ x |
count(x) | นับจำนวนรายการที่ตรงกับ x |
การเรียงลำดับ
หัวข้อที่มีชื่อว่า “การเรียงลำดับ”list.sort() เรียงลำดับใน place และคืนค่า None
ส่ง key function เพื่อเรียงตามเกณฑ์ที่กำหนดเอง
numbers = [5, 2, 8, 1, 9, 3]numbers.sort()print(numbers) # [1, 2, 3, 5, 8, 9]
words = ['banana', 'apple', 'cherry']words.sort(key=len)print(words) # ['apple', 'banana', 'cherry']ใช้ sorted(iterable) แทน .sort() เมื่อต้องการ list ใหม่โดยไม่แก้ไขต้นฉบับ
Tuples — ลำดับที่เปลี่ยนแปลงไม่ได้
หัวข้อที่มีชื่อว่า “Tuples — ลำดับที่เปลี่ยนแปลงไม่ได้”tuple คล้าย list แต่ไม่สามารถแก้ไขหลังสร้างแล้ว ใช้ tuple เพื่อแสดง record ที่คงที่ซึ่งตำแหน่งมีความหมาย
rgb = (255, 128, 0) # สีส้มpoint = (3.0, 4.0) # พิกัด 2 มิติrow = (1, 'Alice', 42) # แถวในฐานข้อมูลTuple unpacking
หัวข้อที่มีชื่อว่า “Tuple unpacking”Python อนุญาตให้ unpack tuple (หรือ iterable ใด ๆ) ลงในตัวแปรโดยตรง
จำนวนตัวแปรต้องตรงกับความยาว ยกเว้นใช้ * เพื่อรับส่วนที่เหลือ
coords = (10.5, 20.3, 30.1)x, y, z = coordsprint(x, y, z) # 10.5 20.3 30.1
first, *rest = [1, 2, 3, 4, 5]print(first) # 1print(rest) # [2, 3, 4, 5]การเข้าถึง field ของ tuple ด้วย index
หัวข้อที่มีชื่อว่า “การเข้าถึง field ของ tuple ด้วย index”โดยไม่มีชื่อ field ของ tuple จะถูกเข้าถึงด้วย integer index กำหนด constant เพื่อให้อ่านง่าย:
RGB = (255, 128, 0)RED = 0GREEN = 1BLUE = 2
print(RGB[RED]) # 255print(RGB[GREEN]) # 128print(RGB[BLUE]) # 0สำหรับแนวทางที่สะดวกกว่า ใช้ collections.namedtuple หรือ typing.NamedTuple
ตัวอย่างรันได้
หัวข้อที่มีชื่อว่า “ตัวอย่างรันได้”# --- list mutation and sorting ---fruits = ['apple', 'banana', 'cherry']fruits.append('date')fruits.insert(1, 'avocado')print('after insert:', fruits)
fruits.remove('banana')print('after remove:', fruits)
numbers = [5, 2, 8, 1, 9, 3]numbers.sort()print('sorted:', numbers)
words = ['banana', 'apple', 'cherry']words.sort(key=len)print('by length:', words)
# --- tuple unpacking ---coords = (10.5, 20.3, 30.1)x, y, z = coordsprint('unpacked:', x, y, z)
first, *rest = [1, 2, 3, 4, 5]print('first:', first)print('rest:', rest)
# --- named fields via index constants ---RGB = (255, 128, 0)print('red:', RGB[0], 'green:', RGB[1], 'blue:', RGB[2])Loading Python runtime (first run only)…