Collections
Collections: โครงสร้างข้อมูลของ Python ที่คุณจะใช้ทุกวัน
หัวข้อที่มีชื่อว่า “Collections: โครงสร้างข้อมูลของ Python ที่คุณจะใช้ทุกวัน”Python มี collection แบบ built-in อยู่สี่ชนิดคือ list, tuple, dict และ set ในฐานะ TypeScript developer คุณมีภาพในหัวของทั้งสี่ตัวอยู่แล้ว การเทียบจึงใกล้เคียงกันมาก แต่ฝั่ง Python แต่ละตัวก็มีจุดเด่นของตัวเอง
| Python | TypeScript | ความต่างสำคัญ |
|---|---|---|
list | Array | เปลี่ยนแปลงได้ (mutable), มีลำดับ |
tuple | Readonly array / [T, U] | เปลี่ยนแปลงไม่ได้ (immutable), ความยาวคงที่ |
dict | Record<K,V> / object / Map | key-value ที่เปลี่ยนแปลงได้ |
set | Set | ค่าที่ไม่ซ้ำกันและไม่มีลำดับ |
list — Array ของ Python
หัวข้อที่มีชื่อว่า “list — Array ของ Python”// TypeScript Arrayconst nums: number[] = [1, 2, 3, 4, 5];
nums.push(6);nums.splice(0, 1); // remove first element
console.log(nums[0]); // 2console.log(nums.length); // 5
const doubled = nums.map((n) => n * 2);const evens = nums.filter((n) => n % 2 === 0);# Python listnums: list[int] = [1, 2, 3, 4, 5]
nums.append(6) # pushnums.pop(0) # remove first element
print(nums[0]) # 2print(len(nums)) # 5
doubled = [n * 2 for n in nums] # list comprehensionevens = [n for n in nums if n % 2 == 0]List comprehension ([expr for x in iterable if condition]) คือสไตล์ idiomatic ของ Python งานแปลงค่าง่าย ๆ ควรเลือกท่านี้ก่อน map/filter เสมอ
dict — Record / Map ของ Python
หัวข้อที่มีชื่อว่า “dict — Record / Map ของ Python”// TypeScript object / Recordconst user: Record<string, unknown> = { name: "Alice", age: 30,};
user["role"] = "admin"; // add keydelete user["age"]; // remove key
console.log(user["name"]); // Aliceconsole.log(user["missing"] ?? "n/a"); // n/a (nullish coalescing)
for (const [k, v] of Object.entries(user)) { console.log(k, v);}# Python dictuser: dict[str, object] = { "name": "Alice", "age": 30,}
user["role"] = "admin" # add keydel user["age"] # remove key
print(user["name"]) # Aliceprint(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
set — ค่าที่ไม่ซ้ำกัน
หัวข้อที่มีชื่อว่า “set — ค่าที่ไม่ซ้ำกัน”// TypeScript Setconst tags = new Set<string>(["python", "web", "python"]);tags.add("api");
console.log(tags.has("python")); // trueconsole.log(tags.size); // 3tags.delete("web");# Python set — literal syntax with {}tags: set[str] = {"python", "web", "python"} # duplicate removedtags.add("api")
print("python" in tags) # Trueprint(len(tags)) # 3tags.discard("web") # remove without error if absentSlicing — ฟีเจอร์เด็ดของ Python สำหรับ sequence
หัวข้อที่มีชื่อว่า “Slicing — ฟีเจอร์เด็ดของ Python สำหรับ sequence”Slicing ของ Python ดึง sub-sequence ออกมาด้วย [start:stop:step] ฝั่ง TypeScript ไม่มีตัวเทียบตรง ๆ เพราะ .slice() บน array ไม่มีพารามิเตอร์ step และไม่รองรับ index ติดลบแบบเดียวกัน
// TypeScriptconst 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 slicing — works on list, tuple, and strnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4] — indices 2,3,4print(nums[-3:]) # [7, 8, 9] — last 3print(nums[::-1]) # reversed — step of -1print(nums[::2]) # [0,2,4,6,8] — every otherprint(nums[1:8:2]) # [1,3,5,7] — start:stop:step
# Strings too!s = "Hello, World!"print(s[:5]) # Helloprint(s[-6:]) # World!ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”# listnums = [1, 2, 3, 4, 5]print(nums[1:4]) # [2, 3, 4]print(nums[::-1]) # reversednums.append(6)print(nums)
# list comprehensiondoubled = [n * 2 for n in nums]print(doubled)
# tuple (immutable)point = (10, 20)x, y = pointprint(f"x={x}, y={y}")
# dictuser = {"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}")
# settags = {"python", "web", "python"}tags.add("api")print(tags)print("python" in tags)Loading Python runtime (first run only)…