ขุมสมบัติที่ซ่อนอยู่ใน Python: รวม Built-in Functions และ Standard Library ที่ควรรู้

หลายคนที่เริ่มเรียน Python มักรู้จักเพียง print(), input(), for, if หรือ list เท่านั้น

แต่ความจริงแล้ว Python มี "ขุมสมบัติ" ซ่อนอยู่จำนวนมากใน Built-in Functions และ Standard Library ที่ติดตั้งมาพร้อมภาษา ไม่ต้องลงแพ็กเกจเพิ่มแม้แต่นิดเดียว

ยิ่งรู้จักเครื่องมือเหล่านี้มากขึ้น คุณจะยิ่งเขียนโค้ดสั้นลง อ่านง่ายขึ้น และแก้ปัญหาได้เร็วขึ้น


1. การจัดการข้อมูล (Data Processing)

zip()

จับคู่ข้อมูลหลายชุดเข้าด้วยกัน

names = ["Alice", "Bob", "Charlie"]
scores = [80, 90, 95]

for name, score in zip(names, scores):
print(name, score)

ผลลัพธ์

Alice 80
Bob 90
Charlie 95

enumerate()

วนลูปพร้อมรับ Index

fruits = ["apple", "banana", "orange"]

for idx, fruit in enumerate(fruits, start=1):
print(idx, fruit)

ผลลัพธ์

1 apple
2 banana
3 orange

any()

มีอย่างน้อยหนึ่งค่าเป็นจริง

any([0, 0, 5])

ผลลัพธ์

True

all()

ทุกค่าต้องเป็นจริง

all([1, 2, 3])

ผลลัพธ์

True

min() / max()

หาค่าสูงสุดหรือต่ำสุดตามเงื่อนไข

words = ["cat", "elephant", "dog"]

max(words, key=len)

ผลลัพธ์

'elephant'

sorted()

เรียงข้อมูลแบบกำหนดเงื่อนไข

sorted(words, key=len)

ผลลัพธ์

['cat', 'dog', 'elephant']

sum()

รวมข้อมูลใน Iterable

sum(range(101))

ผลลัพธ์

5050

2. Functional Programming

map()

แปลงข้อมูลทั้งชุด

list(map(int, ["1", "2", "3"]))

ผลลัพธ์

[1, 2, 3]

filter()

กรองข้อมูล

list(filter(lambda x: x % 2 == 0,
[1,2,3,4,5]))

ผลลัพธ์

[2, 4]

reduce()

สะสมค่าทีละขั้น

from functools import reduce

reduce(lambda a,b: a+b,
[1,2,3,4])

ผลลัพธ์

10

3. การจัดการข้อความ (String Processing)

split()

"apple,banana".split(",")

ผลลัพธ์

['apple', 'banana']

join()

",".join(["A","B","C"])

ผลลัพธ์

A,B,C

partition()

email = "user@gmail.com"

name, _, domain = email.partition("@")

ผลลัพธ์

name = "user"
domain = "gmail.com"

replace()

"hello".replace("l","X")

ผลลัพธ์

'heXXo'

removeprefix()

"https://example.com".removeprefix(
"https://"
)

ผลลัพธ์

'example.com'

removesuffix()

"report.pdf".removesuffix(".pdf")

ผลลัพธ์

'report'

casefold()

เปรียบเทียบข้อความแบบไม่สนตัวพิมพ์

"HELLO".casefold() == "hello".casefold()

ผลลัพธ์

True

translate()

ลบหรือแทนที่ตัวอักษรจำนวนมาก

text = "Hello, World!"

table = str.maketrans("", "", ",!")
print(text.translate(table))

ผลลัพธ์

Hello World

4. การสุ่ม (Random)

import random

randint()

random.randint(1, 10)

ผลลัพธ์ตัวอย่าง

7

choice()

random.choice(
["แดง","เขียว","น้ำเงิน"]
)

ผลลัพธ์ตัวอย่าง

'เขียว'

sample()

สุ่มโดยไม่ซ้ำ

random.sample(range(1,50), 6)

ผลลัพธ์ตัวอย่าง

[3, 8, 15, 22, 31, 45]

shuffle()

cards = [1,2,3,4,5]

random.shuffle(cards)

print(cards)

ผลลัพธ์ตัวอย่าง

[3,1,5,2,4]

choices()

สุ่มแบบมีน้ำหนัก

random.choices(
["ทอง","เงิน","ทองแดง"],
weights=[1,5,20],
k=10
)

5. คณิตศาสตร์และสถิติ

math

import math

math.sqrt(16)

ผลลัพธ์

4.0

divmod()

hours, mins = divmod(125, 60)

ผลลัพธ์

hours = 2
mins = 5

statistics

from statistics import (
mean,
median,
mode
)

data = [1,2,3,4,100]
mean(data)

ผลลัพธ์

22
median(data)

ผลลัพธ์

3

6. วันที่และเวลา (datetime)

เวลาปัจจุบัน

from datetime import datetime

datetime.now()

strftime()

แปลงเป็นข้อความ

datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)

ผลลัพธ์

2026-06-04 15:30:00

strptime()

แปลงข้อความเป็น Date

datetime.strptime(
"2026-06-04",
"%Y-%m-%d"
)

timedelta

from datetime import timedelta

tomorrow = datetime.now() + timedelta(days=1)

7. การจัดการไฟล์

open()

with open("data.txt") as f:
print(f.read())

pathlib

อ่านไฟล์

from pathlib import Path

Path("data.txt").read_text()

เขียนไฟล์

Path("log.txt").write_text("Hello")

ค้นหาไฟล์

Path(".").glob("*.txt")

8. Collections ที่ทรงพลัง

Counter

นับความถี่ข้อมูล

from collections import Counter

Counter("1122333444")

ผลลัพธ์

Counter({
'4':4,
'3':3,
'1':2,
'2':2
})

defaultdict

สร้างค่าเริ่มต้นให้อัตโนมัติ

from collections import defaultdict

groups = defaultdict(list)

groups["A"].append("Alice")
groups["A"].append("Anna")

print(groups)

ผลลัพธ์

{
'A':['Alice','Anna']
}

deque

Queue ประสิทธิภาพสูง

from collections import deque

q = deque(["A","B","C"])

q.popleft()

ผลลัพธ์

'A'

เหลือ

deque(['B','C'])

namedtuple

Struct แบบเบา ๆ

from collections import namedtuple

Person = namedtuple(
"Person",
["name","age"]
)

p = Person("Alice", 20)

print(p.name)

ผลลัพธ์

Alice

เข้าถึงข้อมูลแบบ Attribute ได้โดยไม่ต้องสร้าง Class เต็มรูปแบบ


9. itertools : อาวุธลับของ Python

product()

ทุกความเป็นไปได้

from itertools import product

list(product([1,2], ["A","B"]))

ผลลัพธ์

[
(1,'A'),
(1,'B'),
(2,'A'),
(2,'B')
]

combinations()

เลือกโดยไม่สนลำดับ

list(combinations([1,2,3],2))

ผลลัพธ์

[
(1,2),
(1,3),
(2,3)
]

permutations()

เลือกโดยสนลำดับ

list(permutations([1,2,3],2))

ผลลัพธ์

[
(1,2),
(1,3),
(2,1),
(2,3),
(3,1),
(3,2)
]

groupby()

จัดกลุ่มข้อมูลที่อยู่ติดกัน

from itertools import groupby

for k, g in groupby("AAABBBCC"):
print(k, list(g))

ผลลัพธ์

A ['A','A','A']
B ['B','B','B']
C ['C','C']

pairwise()

ดูสมาชิกที่อยู่ติดกัน

from itertools import pairwise

list(pairwise([10,20,30,40]))

ผลลัพธ์

[
(10,20),
(20,30),
(30,40)
]

cycle()

วนไม่สิ้นสุด

from itertools import cycle

colors = cycle(
["แดง","เขียว","น้ำเงิน"]
)

ผลลัพธ์เมื่อเรียกหลายครั้ง

แดง
เขียว
น้ำเงิน
แดง
เขียว
น้ำเงิน
...

10. Cache และ Performance

lru_cache

from functools import lru_cache

@lru_cache
def fib(n):
...

เหมาะกับ Recursive Function ที่เรียกซ้ำ ๆ


11. Generator และ Streaming

yield

def numbers():
yield 1
yield 2
yield 3
g = numbers()

next(g)

ผลลัพธ์

1

เรียกอีกครั้ง

2

เรียกอีกครั้ง

3

ช่วยประหยัด RAM อย่างมากเมื่อจัดการข้อมูลขนาดใหญ่


12. Unpacking

*

nums = [1,2,3]

print(*nums)

ผลลัพธ์

1 2 3

**

config = {
"host":"localhost",
"port":8080
}
start_server(**config)

เทียบเท่า

start_server(
host="localhost",
port=8080
)

Extended Unpacking

a, *middle, z = [1,2,3,4,5]

ผลลัพธ์

a = 1
middle = [2,3,4]
z = 5

13. Debugging และ Inspection

repr()

repr("hello\nworld")

ผลลัพธ์

'hello\\nworld'

type()

type(123)

ผลลัพธ์

<class 'int'>

isinstance()

isinstance(123, int)

ผลลัพธ์

True

id()

id(obj)

ดู Identity ของ Object


hash()

hash("หวย")

ใช้สร้าง Hash Key


14. Formatting

f-string

name = "Alice"

f"Hello {name}"

ผลลัพธ์

Hello Alice

จัดรูปแบบตัวเลข

price = 1234567.89

f"{price:,.2f}"

ผลลัพธ์

1,234,567.89

จัดรูปแบบวันที่

f"{datetime.now():%Y-%m-%d}"

ผลลัพธ์

2026-06-04

สรุป

ถ้าคุณกำลังเรียน Python และอยากเพิ่มพลังการเขียนโค้ดอย่างก้าวกระโดด ให้เริ่มจากชุดนี้ก่อน

  1. zip()
  2. enumerate()
  3. Counter
  4. defaultdict
  5. deque
  6. pathlib
  7. itertools
  8. yield
  9. datetime
  10. lru_cache

เพียงเข้าใจเครื่องมือเหล่านี้ คุณจะเริ่มมองเห็นว่า Python ไม่ได้เป็นแค่ภาษาที่เขียนง่าย แต่เป็นภาษาที่เต็มไปด้วย "เครื่องมือสำเร็จรูป" ที่ช่วยลดโค้ดจำนวนมากให้เหลือเพียงไม่กี่บรรทัด และนี่คือเหตุผลที่ Python ได้รับความนิยมอย่างต่อเนื่องในงาน Automation, Data Science, Web Development และ AI จนถึงปัจจุบันครับ

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

รับติดตั้งระบบป้ายโฆษณาดิจิตอล Digital Signage ตั้งเวลาทำงานและควบคุมผ่าน Internet ได้

แจกฟรี ระบบแสดงคิวงาน สำหรับร้านนวด สปา หรือ ร้านทำผม

บริการออกแบบ Character Agent สำหรับธุรกิจ

ป้ายดิจิตอลที่โต้ตอบได้