ข้ามไปยังเนื้อหา

Collections

Collections: โครงสร้างข้อมูลของ Python ที่คุณจะใช้ทุกวัน

หัวข้อที่มีชื่อว่า “Collections: โครงสร้างข้อมูลของ Python ที่คุณจะใช้ทุกวัน”

Python มี collection แบบ built-in อยู่สี่ชนิดคือ list, tuple, dict และ set ในฐานะ TypeScript developer คุณมีภาพในหัวของทั้งสี่ตัวอยู่แล้ว การเทียบจึงใกล้เคียงกันมาก แต่ฝั่ง Python แต่ละตัวก็มีจุดเด่นของตัวเอง

PythonTypeScriptความต่างสำคัญ
listArrayเปลี่ยนแปลงได้ (mutable), มีลำดับ
tupleReadonly array / [T, U]เปลี่ยนแปลงไม่ได้ (immutable), ความยาวคงที่
dictRecord<K,V> / object / Mapkey-value ที่เปลี่ยนแปลงได้
setSetค่าที่ไม่ซ้ำกันและไม่มีลำดับ
TypeScript
// TypeScript Array
const nums: number[] = [1, 2, 3, 4, 5];
nums.push(6);
nums.splice(0, 1); // remove first element
console.log(nums[0]); // 2
console.log(nums.length); // 5
const doubled = nums.map((n) => n * 2);
const evens = nums.filter((n) => n % 2 === 0);
Python
# Python list
nums: list[int] = [1, 2, 3, 4, 5]
nums.append(6) # push
nums.pop(0) # remove first element
print(nums[0]) # 2
print(len(nums)) # 5
doubled = [n * 2 for n in nums] # list comprehension
evens = [n for n in nums if n % 2 == 0]

List comprehension ([expr for x in iterable if condition]) คือสไตล์ idiomatic ของ Python งานแปลงค่าง่าย ๆ ควรเลือกท่านี้ก่อน map/filter เสมอ

TypeScript
// TypeScript object / Record
const user: Record<string, unknown> = {
name: "Alice",
age: 30,
};
user["role"] = "admin"; // add key
delete user["age"]; // remove key
console.log(user["name"]); // Alice
console.log(user["missing"] ?? "n/a"); // n/a (nullish coalescing)
for (const [k, v] of Object.entries(user)) {
console.log(k, v);
}
Python
# Python dict
user: dict[str, object] = {
"name": "Alice",
"age": 30,
}
user["role"] = "admin" # add key
del user["age"] # remove key
print(user["name"]) # Alice
print(user.get("missing", "n/a")) # n/a (safe lookup)
for key, value in user.items():
print(key, value)

ถ้าคีย์อาจไม่มีอยู่จริง ให้ใช้ .get(key, default) แทน dict[key] เพราะจะคืนค่า default ให้แทนการโยน KeyError

TypeScript
// TypeScript Set
const tags = new Set<string>(["python", "web", "python"]);
tags.add("api");
console.log(tags.has("python")); // true
console.log(tags.size); // 3
tags.delete("web");
Python
# Python set — literal syntax with {}
tags: set[str] = {"python", "web", "python"} # duplicate removed
tags.add("api")
print("python" in tags) # True
print(len(tags)) # 3
tags.discard("web") # remove without error if absent

Slicing ของ Python ดึง sub-sequence ออกมาด้วย [start:stop:step] ฝั่ง TypeScript ไม่มีตัวเทียบตรง ๆ เพราะ .slice() บน array ไม่มีพารามิเตอร์ step และไม่รองรับ index ติดลบแบบเดียวกัน

TypeScript
// TypeScript
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(nums.slice(2, 5)); // [2, 3, 4]
console.log(nums.slice(-3)); // [7, 8, 9]
// No step parameter in .slice()
Python
# Python slicing — works on list, tuple, and str
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4] — indices 2,3,4
print(nums[-3:]) # [7, 8, 9] — last 3
print(nums[::-1]) # reversed — step of -1
print(nums[::2]) # [0,2,4,6,8] — every other
print(nums[1:8:2]) # [1,3,5,7] — start:stop:step
# Strings too!
s = "Hello, World!"
print(s[:5]) # Hello
print(s[-6:]) # World!
# list
nums = [1, 2, 3, 4, 5]
print(nums[1:4]) # [2, 3, 4]
print(nums[::-1]) # reversed
nums.append(6)
print(nums)
# list comprehension
doubled = [n * 2 for n in nums]
print(doubled)
# tuple (immutable)
point = (10, 20)
x, y = point
print(f"x={x}, y={y}")
# dict
user = {"name": "Alice", "age": 30}
user["role"] = "admin"
print(user.get("name"))
print(user.get("missing", "default"))
for k, v in user.items():
print(f" {k}: {v}")
# set
tags = {"python", "web", "python"}
tags.add("api")
print(tags)
print("python" in tags)
collection ชนิดไหนของ Python ใกล้เคียง `Map<string, number>` ของ TypeScript มากที่สุด?
`nums[::2]` คืนค่าอะไรสำหรับ `nums = [0,1,2,3,4,5,6]`?
method ไหนดึงค่าจาก dict ได้อย่างปลอดภัยโดยไม่โยน KeyError?
เขียน `t = (1, 2, 3); t[0] = 99` แล้วเกิดอะไรขึ้น?