ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
စာရင်းတစ်ခုကို ကြည့်ပြီး "ဒီထဲက တစ်ခုချင်းစီကို နှစ်ဆလုပ်ပြီး အသစ်ရေးပေး" ဒါမှမဟုတ် "ဈေးနှုန်း ၁၀၀၀ ကျော်တာတွေပဲ ရွေးပေး" လို့ လူတစ်ယောက်ကို ခိုင်းရင် စကားတစ်ကြောင်းတည်းနဲ့ ပြောလို့ရပါတယ်။ Comprehension ဆိုတာ Python ကို အဲဒီလို စကားတစ်ကြောင်းတည်းနဲ့ ခိုင်းတဲ့ နည်းပါ။
[x * 2 for x in numbers] ကို "numbers ထဲက x တိုင်းအတွက် x * 2 ကို list တစ်ခုထဲ စုပေး" လို့ ဖတ်ပါတယ်။ ကွင်းအမျိုးအစားက ရလဒ်ကို ဆုံးဖြတ်ပါတယ် — [ ] ဆို list၊ { } ဆို set ဒါမှမဟုတ် dict ရပါတယ်။ မူရင်း collection ကို ဘာမှ မပြောင်းလဲဘဲ အသစ်တစ်ခု ထုတ်ပေးတာပါ။
Problem → Why → Solution
ပြဿနာ: append loop တွေက အဓိပ္ပာယ်ကို ဖုံးထားတယ်
User စာရင်းကနေ active ဖြစ်တဲ့သူတွေရဲ့ နာမည်နဲ့ email ကို ထုတ်ချင်တယ် ဆိုပါစို့။ Loop ရိုးရိုးနဲ့ဆို collection တစ်ခုစီအတွက် list အလွတ်ဖန်တီး၊ loop ပတ်၊ if စစ်၊ append လုပ်ဆိုတဲ့ လေးကြောင်း ပုံစံကို ထပ်ခါထပ်ခါ ရေးရပါတယ်။ အောက်က code မှာ ဒုတိယ loop က active စစ်တာကို မေ့သွားလို့ inactive user တွေဆီပါ email ပို့မိပါလိမ့်မယ်။
active_names = []
for user in users:
if user["active"]:
active_names.append(user["name"].title())
emails = []
for user in users:
emails.append(user["email"].lower()) # bug: inactive users includedဘာကြောင့် ဒီ bug က လွယ်လွယ် လွတ်သွားတာလဲ
Loop တစ်ခုချင်းစီရဲ့ အဓိကအလုပ်က "ဘာကို စုမလဲ၊ ဘယ်ဟာကို ချန်မလဲ" ဆိုတဲ့ အချက်နှစ်ချက်ပဲ ဖြစ်ပေမယ့် ဖတ်တဲ့သူက body တစ်ခုလုံးကို ဖတ်မှ သိရပါတယ်။ ဒါကြောင့် ဆင်တူ loop နှစ်ခုကြားက condition တစ်ခု ပျောက်နေတာကို review မှာ မမြင်မိတတ်ပါဘူး။ Comprehension က အဲဒီ အချက်နှစ်ချက်ကို expression တစ်ခုထဲမှာ ဘေးချင်းကပ် ပြထားလို့ ကွာခြားချက်ကို ချက်ချင်း မြင်ရပါတယ်။
Core concept: comprehension တစ်ခုရဲ့ အစိတ်အပိုင်းများ
List comprehension မှာ အပိုင်းသုံးပိုင်း ရှိပါတယ် — [expression for item in iterable if condition]။ for item in iterable က item တွေကို တစ်ခုချင်း ထုတ်ပေးပြီး if condition (optional) က False ဖြစ်တဲ့ item တွေကို ချန်ခဲ့ပါတယ်။ ကျန်တဲ့ item တိုင်းအတွက် ရှေ့ဆုံးက expression ကို တွက်ပြီး ရလဒ်ကို list အသစ်ထဲ ထည့်ပါတယ်။ ရေးတဲ့ အစဉ်က expression အရင်လာပေမယ့် run တဲ့ အစဉ်က for, if, expression ဖြစ်ပါတယ်။
ဒါက loop တစ်ခုနဲ့ အတိအကျ ညီမျှပါတယ် — result = []; for item in iterable: if condition: result.append(expression)။ Comprehension တစ်ခုကို နားမလည်ရင် ဒီ loop ပုံစံ ပြန်ချရေးကြည့်တာက အမြန်ဆုံး နည်းပါ။ for clause နှစ်ခု ပါရင် ဘယ်ဘက်က for က အပြင် loop၊ ညာဘက်က for က အတွင်း loop ဖြစ်ပါတယ်၊ nested loop ရေးတဲ့ အစဉ်အတိုင်းပါပဲ။
| ရေးပုံ | ရလဒ် |
|---|---|
| [x * 2 for x in data] | list — အစဉ်နဲ့ ထပ်နေတာတွေ ကျန်ပါတယ် |
| {x % 3 for x in data} | set — ထပ်နေတဲ့ ရလဒ်တွေ တစ်ခုတည်း ဖြစ်သွားပါတယ် |
| {k: v for k, v in pairs} | dict — key ထပ်ရင် နောက်ဆုံးတန်ဖိုး နိုင်ပါတယ် |
| (x * 2 for x in data) | generator — လိုမှ တစ်ခုချင်း တွက်ပါတယ် |
Generator expression က list တစ်ခုလုံးကို memory ထဲ မဆောက်ပါဘူး၊ sum(), max(), any() လို function က တောင်းတော့မှ item တစ်ခုချင်း ထုတ်ပေးပါတယ်။ ဒါကြောင့် row သန်းချီရှိတဲ့ data ကို ပေါင်းတာလို aggregate တွေအတွက် သင့်တော်ပါတယ်။ ဒါပေမယ့် တစ်ကြိမ်ပဲ ပတ်လို့ရပါတယ် — ကုန်သွားရင် ဗလာ ဖြစ်သွားပါတယ်။
Python 3 မှာ comprehension ရဲ့ loop variable က ကိုယ်ပိုင် scope ထဲမှာပဲ ရှိလို့ အပြင်ဘက်က နာမည်တူ variable ကို မထိခိုက်ပါဘူး။ Expression ကို item တစ်ခုစီအတွက် တစ်ကြိမ်ပဲ တွက်ပါတယ်၊ ဒါကြောင့် condition ထဲရော expression ထဲမှာပါ ဈေးကြီးတဲ့ function ကို နှစ်ခါ ခေါ်နေရင် walrus operator (:=) နဲ့ ရလဒ်ကို သိမ်းထားလို့ ရပါတယ်။
- Iterable ထဲက item တစ်ခု ယူ
- if clause False ဆို ချန်ခဲ့
- Expression နဲ့ ရလဒ်ကို တွက်
- list, set ဒါမှမဟုတ် dict ထဲ စု
if clause က ဇကာ (item တွေကို ချန်ခဲ့တယ်)၊ ရှေ့က expression က စက် (item တိုင်းကို ပုံပြောင်းတယ်) ပါ။
အထွေထွေ ပုံစံ
new_list = [expression for item in iterable if condition]
new_set = {expression for item in iterable if condition}
new_dict = {key_expr: value_expr for item in iterable if condition}
lazy_items = (expression for item in iterable if condition)
# two for clauses: the left one is the outer loop
pairs = [(a, b) for a in outer for b in inner]ကွင်းအမျိုးအစားက ရလဒ် type ကို ဆုံးဖြတ်ပါတယ်၊ key_expr: value_expr ပုံစံ ပါမှ dict ဖြစ်ပါတယ်။ if condition က အမြဲ optional ဖြစ်ပြီး နောက်ဆုံးမှာပဲ ရှိရပါတယ်။ ( ) နဲ့ ရေးရင် tuple မဟုတ်ဘဲ generator ရပါတယ်။
Example: comprehension အမျိုးအစား အားလုံး
ဒီ example က range() နဲ့ စကားလုံး စာရင်းကနေ comprehension ပုံစံ ငါးမျိုးကို တစ်ခုချင်း ပြပါတယ်။ Line တစ်ခုစီကို run မလုပ်ခင် ညီမျှတဲ့ loop ကို စိတ်ထဲမှာ ပြန်ချရေးပြီး output ကို ခန့်မှန်းကြည့်ပါ။
# List comprehension: transform every item
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")
# With a condition: keep only some items
evens = [x for x in range(20) if x % 2 == 0]
print(f"Evens: {evens}")
# Nested: one inner list per outer item
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(f"Matrix: {matrix}")
# Dictionary comprehension: key: value pairs
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Dict: {square_dict}")
# Set comprehension: duplicate results collapse
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(f"Lengths: {unique_lengths}")
# Generator expression: lazy, no list is built
total = sum(x**2 for x in range(10))
print(f"Sum of squares: {total}")Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Transform
squares = [x**2 for x in range(10)]if clause မပါလို့ item ဆယ်ခုလုံး ဖြတ်သွားပြီး တစ်ခုစီကို x**2 နဲ့ ပုံပြောင်းပါတယ်။ ရလဒ် list မှာ element ဆယ်ခု ရှိပါတယ်။
- Filter
evens = [x for x in range(20) if x % 2 == 0]Expression က x ကိုယ်တိုင်ပဲ ဖြစ်လို့ ပုံမပြောင်းဘဲ စစ်ထုတ်ရုံပါ။ x % 2 == 0 မဟုတ်တဲ့ မဂဏန်းတွေကို ချန်ခဲ့ပါတယ်။
- Nested
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]အပြင်ဘက် comprehension ရဲ့ expression ကိုယ်တိုင်က comprehension တစ်ခု ဖြစ်နေပါတယ်။ i တစ်ခုစီအတွက် row list အသစ်တစ်ခု ဆောက်လို့ list of lists ရပါတယ်။
- Dict
square_dict = {x: x**2 for x in range(1, 6)}Colon ပါလို့ dict ဖြစ်ပါတယ်။ x က key၊ x**2 က value ပါ။
- Set
unique_lengths = {len(word) for word in ["hello", "world", "python"]}"hello" နဲ့ "world" နှစ်ခုလုံး length 5 ဖြစ်လို့ set ထဲမှာ 5 တစ်ခုပဲ ကျန်ပါတယ်။ ရလဒ်က {5, 6} ပါ။
- Generator
total = sum(x**2 for x in range(10))Function call ရဲ့ argument တစ်ခုတည်း ဖြစ်ရင် ကွင်းထပ်မလိုပါဘူး။ sum() က square တွေကို တစ်ခုချင်း ယူပေါင်းလို့ list မဆောက်ဘဲ 285 ရပါတယ်။
Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Evens: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Matrix: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Dict: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Lengths: {5, 6}
Sum of squares: 285Filter if နဲ့ if-else ရွေးချယ်မှု ကွာခြားချက်
if က နေရာနှစ်ခုမှာ ပေါ်လာနိုင်ပြီး အဓိပ္ပာယ် လုံးဝ ကွဲပါတယ်။ နောက်ဆုံးက if ကတော့ filter ဖြစ်ပြီး item တွေကို ဖယ်ထုတ်လို့ ရလဒ်က တိုသွားနိုင်ပါတယ်၊ else မပါရပါဘူး။ ရှေ့က a if condition else b ကတော့ expression ရဲ့ အစိတ်အပိုင်း (conditional expression) ဖြစ်ပြီး item တိုင်းကို ထားကာ တန်ဖိုးနှစ်ခုထဲက တစ်ခု ရွေးပါတယ်၊ else မဖြစ်မနေ လိုပါတယ်။ Nested for clause တွေကလည်း ဒီ snippet ထဲမှာ ပါပါတယ်။
nums = [3, -1, 4, -5]
positives = [n for n in nums if n > 0] # filter: drops items
labels = ["pos" if n > 0 else "neg" for n in nums] # choose: keeps every item
print(positives, labels)
grid = [[1, 2], [3, 4]]
flat = [cell for row in grid for cell in row] # outer loop comes first
print(flat)လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
API ကနေ ပြန်လာတဲ့ JSON record တွေ၊ CSV row တွေ၊ database query ရလဒ်တွေကို လိုတဲ့ ပုံစံ ပြောင်းတဲ့ နေရာတိုင်းမှာ comprehension တွေကို တွေ့ရပါတယ်။ ဥပမာ — ပေးချေပြီးသား order တွေရဲ့ စုစုပေါင်းကို list နဲ့ ထုတ်တာ၊ ဝယ်သူ နာမည်တွေကို set နဲ့ ထပ်မနေအောင် စုတာ၊ {order["id"]: order for order in orders} နဲ့ id ကနေ record ကို အမြန်ရှာလို့ရတဲ့ lookup table ဆောက်တာ စသည်ပါ။ နောက်ဆုံး ပုံစံက list ထဲမှာ ထပ်ခါထပ်ခါ ရှာနေတဲ့ code ကို dict lookup တစ်ခုတည်း ဖြစ်အောင် ပြောင်းပေးလို့ performance ပါ တိုးပါတယ်။
Data များတဲ့ report တွေမှာ sum(row["amount"] for row in rows) လို generator expression ကို သုံးပါတယ်၊ ဒါမှ row သန်းချီကို memory ထဲ list အဖြစ် ထပ်မကူးရပါဘူး။ any(error for error in results) နဲ့ all(...) ကလည်း အဖြေ သိတာနဲ့ ချက်ချင်း ရပ်လို့ ပိုမြန်ပါတယ်။ Team code review တွေမှာတော့ comprehension တစ်ကြောင်းက မျက်လုံးတစ်ချက်နဲ့ နားမလည်ရင် loop ရိုးရိုး ပြန်ရေးခိုင်းတာ အဖြစ်များပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. Side effect အတွက် comprehension သုံးတာ
[print(name) for name in names] က print လုပ်ပေမယ့် None တွေ ပြည့်နေတဲ့ list တစ်ခုကို အလကား ဆောက်ပြီး ပစ်လိုက်ပါတယ်။ Comprehension က collection အသစ် ထုတ်ဖို့ပါ၊ print ထုတ်တာ၊ file ရေးတာ၊ database update လုပ်တာလို အလုပ်တွေအတွက် for loop ရိုးရိုးကို သုံးပါ။
2. if-else ကို နောက်ဆုံးမှာ ထားတာ
[x for x in nums if x > 0 else 0] က SyntaxError ပါ။ Item တိုင်းကို ထားပြီး တန်ဖိုး ရွေးချင်ရင် conditional expression ကို ရှေ့ကို ရွှေ့ပါ — [x if x > 0 else 0 for x in nums]။ Item တွေကို ဖယ်ချင်တာဆိုရင်တော့ else မပါတဲ့ filter if ကို နောက်ဆုံးမှာ ထားပါ။
3. Generator ကို နှစ်ခါ ပတ်တာ
squares = (x * x for x in nums) ပြီးရင် sum(squares) က မှန်ပေမယ့် နောက်က max(squares) က "max() iterable argument is empty" ValueError ပေးပါတယ်၊ generator ကုန်သွားပြီ ဖြစ်လို့ပါ။ ရလဒ်ကို အကြိမ်ကြိမ် သုံးရမယ်ဆိုရင် list comprehension နဲ့ သိမ်းထားပါ။
4. Dict comprehension မှာ key ထပ်နေတာ
Key တူတာ နှစ်ခါ ထွက်လာရင် error မပေးဘဲ နောက်ဆုံးတန်ဖိုးက အရင်တန်ဖိုးကို ဖုံးသွားပါတယ်။ Key တစ်ခုအောက်မှာ item အများကြီး စုချင်ရင် loop နဲ့ dict.setdefault() ဒါမှမဟုတ် collections.defaultdict(list) ကို သုံးပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- for clause နှစ်ခု သို့မဟုတ် if နှစ်ခုထက် များလာရင် loop သို့မဟုတ် helper function နဲ့ ခွဲရေးပါ။
- sum(), any(), max() ထဲကို တိုက်ရိုက် ပို့မယ့် ရလဒ်ဆိုရင် list မဆောက်ဘဲ generator expression ကို သုံးပါ။
- Comprehension variable ကို item, row, user လို အဓိပ္ပာယ်ရှိတဲ့ နာမည် ပေးပါ၊ x ကို သင်္ချာ ဥပမာတွေအတွက်ပဲ ထားပါ။
Mini challenge
Mini challenge: order report
Shop တစ်ခုရဲ့ order စာရင်းကနေ comprehension လေးမျိုး သုံးပြီး report တစ်ခု ထုတ်ပါ။ Loop ရိုးရိုးနဲ့ append မသုံးရပါ။
- paid_totals — status "paid" ဖြစ်ပြီး qty > 0 ဖြစ်တဲ့ order တိုင်းရဲ့ qty * price list
- customers — paid order အနည်းဆုံး တစ်ခု ရှိတဲ့ ဝယ်သူ နာမည် set
- status_by_id — order id ကနေ status ကို map လုပ်တဲ့ dict
- revenue — paid order တွေရဲ့ qty * price စုစုပေါင်း၊ list မဆောက်ဘဲ generator နဲ့ တွက်ရမယ်
orders = [
{"id": 101, "customer": "Aye", "qty": 2, "price": 1500, "status": "paid"},
{"id": 102, "customer": "Ko Ko", "qty": 1, "price": 9000, "status": "cancelled"},
{"id": 103, "customer": "Aye", "qty": 3, "price": 2000, "status": "paid"},
{"id": 104, "customer": "Mya", "qty": 0, "price": 4000, "status": "paid"},
]
# TODO: paid_totals = [... for o in orders if ...]
# TODO: customers = {... for o in orders if ...}
# TODO: status_by_id = {key: value for o in orders}
# TODO: revenue = sum(... for o in orders if ...)
# TODO: print the four results (sort the set so the output is stable)ရလဒ်: Script က ဒီလို print ထုတ်ရပါမယ်: Paid totals: [3000, 6000] Customers: ['Aye', 'Mya'] Status by id: {101: 'paid', 102: 'cancelled', 103: 'paid', 104: 'paid'} Revenue: 9000
အရိပ်အမြွက် ကြည့်ရန်
Condition နှစ်ခုကို and နဲ့ ဆက်ပါ။ set ကို print မလုပ်ခင် sorted() နဲ့ list ပြောင်းရင် output အစဉ် မပြောင်းတော့ပါဘူး။ qty 0 ဖြစ်တဲ့ order 104 က revenue ကို ဘာမှ မပေါင်းပေမယ့် Mya ကတော့ customers ထဲ ပါပါတယ်။
အဖြေ ကြည့်ရန်
orders = [
{"id": 101, "customer": "Aye", "qty": 2, "price": 1500, "status": "paid"},
{"id": 102, "customer": "Ko Ko", "qty": 1, "price": 9000, "status": "cancelled"},
{"id": 103, "customer": "Aye", "qty": 3, "price": 2000, "status": "paid"},
{"id": 104, "customer": "Mya", "qty": 0, "price": 4000, "status": "paid"},
]
paid_totals = [o["qty"] * o["price"] for o in orders
if o["status"] == "paid" and o["qty"] > 0]
customers = {o["customer"] for o in orders if o["status"] == "paid"}
status_by_id = {o["id"]: o["status"] for o in orders}
revenue = sum(o["qty"] * o["price"] for o in orders if o["status"] == "paid")
print("Paid totals:", paid_totals)
print("Customers:", sorted(customers))
print("Status by id:", status_by_id)
print("Revenue:", revenue)Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- [expression for item in iterable if condition] ကို for, if, expression အစဉ်နဲ့ run တဲ့ loop တစ်ခုလို ဖတ်ပါ။
- [ ] က list၊ { } က set (key: value ပါရင် dict)၊ ( ) က တစ်ကြိမ်ပဲ ပတ်လို့ရတဲ့ lazy generator ပါ။
- နောက်ဆုံးက if က item ကို ဖယ်ပြီး ရှေ့က a if c else b က item တိုင်းအတွက် တန်ဖိုး ရွေးပါတယ်။
- Side effect ပါရင် ဒါမှမဟုတ် အဆင့်များလာရင် for loop ရိုးရိုးက ပိုရှင်းပါတယ်။
Python Documentation — Functional Programming HOWTO — Python Software Foundation