Iterations and Collections
range() และ enumerate()ทบทวน List, Tuple, Set, Dictionary
การใช้ตัวแปรจำนวนมาก อาจไม่เหมาะกับการทำงานกับข้อมูลจำนวนมาก เช่น
name1, name2, name3, …score1, score2, score3, …ลิสต์ (List) คือการเก็บชุดข้อมูลที่เกี่ยวข้องกันจำนวนหลาย ๆ ตัวให้อยู่ภายใต้ตัวแปรเดียวกัน
Note
ทบทวน: List (Module 4)
data[index]index มีค่าเริ่มต้นเป็น 0 เสมอ — ตำแหน่งแรก (ช่องแรก)index มีค่ามากที่สุดคือ n-1 — ตำแหน่งสุดท้าย เมื่อ n คือจำนวนช่องทั้งหมดลิสต์ใน Python เทียบเคียงได้กับ array ในภาษาคอมพิวเตอร์อื่น ๆ
ตัวแปร List มีความสามารถ/คำสั่งติดตัวที่ช่วยเพิ่มข้อมูลใหม่ให้ List
.append() เพิ่มข้อมูลต่อท้าย List.insert() แทรกข้อมูลในตำแหน่ง index ที่ต้องการนอกจากนี้ยังมี operator ที่ช่วยเพิ่มข้อมูลต่อท้าย List
+ ใช้เชื่อมต่อ List เข้าด้วยกัน (concatenation)* ใช้เพิ่มข้อมูลให้มีหลายชุดตามจำนวนที่ต้องการNote
มีข้อมูลคะแนนสอบ midterm เก็บในตัวแปร score = [91,22,59,62,80,68,40,36,88,56,13,3,90,18]
จงเขียนคำสั่งเรียกใช้ตัวแปร score (พิมพ์ค่าจากตัวแปร ไม่ใช่คัดลอกข้อความ)
Midterm score is [91, 22, …, 18]score → Number of student in section000 = 141st score: 91, last score = 18Sum of the 2nd to 4th score is = 143หาผลรวมคะแนนคนที่ 2 ถึง 4 เหมือนเดิม แต่รอบนี้ให้ slice ช่วงข้อมูลออกมาก่อน เก็บใน sc_temp
ใช้รูปแบบ score[start:stop:step] (จำว่า stop จะไม่รวม item ที่ระบุ)
คิดก่อน: ต้องการ index 1,2,3 — start, stop, step ควรเป็นเท่าใด?
Note
ทบทวน: Slicing list (Module 4)
อยากเก็บคะแนนต้นฉบับไว้โดยแก้ไขไม่ได้ → แปลง score เป็น tuple
แล้วแปลงกลับเป็น list และ คัดลอก ไว้ที่ sc_new
คิดก่อน: การพิมพ์ tuple กับ list ต่างกันที่สัญลักษณ์ใด?
Note
แก้ไขข้อมูลใน sc_new ตามลำดับ
99 ต่อท้าย88 ไว้หน้าสุด3 ออกคิดก่อน: .remove(3) กับ .pop(3) ต่างกันอย่างไร? อันไหนอ้างถึง ค่า อันไหนอ้างถึง index?
sc_new.append(99)
print(f'New score of section 000 after append new value:\n{sc_new}')
sc_new.insert(0, 88)
print(f'New score of section 000 after insert new value:\n{sc_new}')
sc_new.remove(3)
print(f'New score of section 000 after remove value:\n {sc_new}')
sc_new.pop(3)
print(f'New score of section 000 after pop out the 4th student:\n{sc_new}')New score of section 000 after append new value:
[91, 22, 59, 62, 80, 68, 40, 36, 88, 56, 13, 3, 90, 18, 99]
New score of section 000 after insert new value:
[88, 91, 22, 59, 62, 80, 68, 40, 36, 88, 56, 13, 3, 90, 18, 99]
New score of section 000 after remove value:
[88, 91, 22, 59, 62, 80, 68, 40, 36, 88, 56, 13, 90, 18, 99]
New score of section 000 after pop out the 4th student:
[88, 91, 22, 62, 80, 68, 40, 36, 88, 56, 13, 90, 18, 99]int)int, float, string, tupleNote
ทบทวน: Dictionary (Module 4)
จงสร้างตัวแปร Student ชนิด dictionary เพื่อเก็บข้อมูลต่อไปนี้
| key | value |
|---|---|
"name" |
"Thanatip Chankong" |
"ID" |
"4206144" |
"isInter" |
False |
"midterm" |
25 |
'final' value 30'isInter' ออก แล้วเก็บค่าที่ลบไว้ในตัวแปร status.keys() และดู รายการทั้งหมด ด้วย .items()คิดก่อน: .pop('isInter') คืนค่าอะไรกลับมา?
{'name': 'Thanatip Chankong', 'ID': '4206144', 'isInter': False, 'midterm': 25, 'final': 30}
{'name': 'Thanatip Chankong', 'ID': '4206144', 'midterm': 25, 'final': 30}
False
dict_keys(['name', 'ID', 'midterm', 'final'])
dict_items([('name', 'Thanatip Chankong'), ('ID', '4206144'), ('midterm', 25), ('final', 30)])วนซ้ำเพื่อเข้าถึงข้อมูลใน collection
เมื่อมีข้อมูลจำนวนมากใน collection การเข้าถึงทีละ index เองเป็นเรื่องไม่สะดวก
เราสามารถนำ iteration / loop มาช่วยให้การเข้าถึงข้อมูลใน collection สะดวกขึ้นได้
ใช้ While-loop สร้างตัวเลขที่ใช้เป็น index สำหรับ collection
อย่าลืม 3 ส่วนของ while: 1) ค่าตั้งต้น 2) condition 3) อัพเดทค่าแต่ละรอบ
Note
ทบทวน: While-loop (Module 6)
ในทำนองเดียวกัน ใช้ For-loop และ range() สร้างตัวเลข index ได้เช่นกัน
range(start, stop, step) — stop จะหยุดที่ค่าก่อนหน้า stop
Note
นับจำนวนคนที่ได้คะแนน มากกว่า 60 เก็บไว้ในตัวแปร cnt
แล้วแสดง student with score higher than 60 = ... students.
คิดก่อน: ลองทำทั้งแบบ while และแบบ for — โครงสร้างต่างกันอย่างไร?
Note
# Example-4F : ใช้ for-loop
sc_new = [88, 91, 22, 62, 80, 68, 40, 36, 88, 56, 13, 90, 18, 99]
cnt = 0
for i in range(0, len(sc_new), 1):
if sc_new[i] > 60:
cnt = cnt + 1
print(f"student with score higher than 60 = {cnt} students.")
# Example-4W : ใช้ while-loop (ได้ผลเท่ากัน)
i = 0; cnt = 0
while i <= len(sc_new)-1:
if sc_new[i] > 60:
cnt = cnt + 1
i = i + 1
print(f"student with score higher than 60 = {cnt} students.")ค้นหานักศึกษาที่ได้คะแนน น้อยกว่าหรือเท่ากับ 40 ถ้าเจอให้แสดง Student at index=... is Fail (F)
คิดก่อน: ต้องการแสดง ตำแหน่ง (index) ด้วย — ควรใช้ loop แบบสร้าง index หรือแบบเข้าถึงตรง?
for-loop = หยิบข้อมูลในคอลเลกชันมาทำทีละชิ้น เหมือนสายพานลำเลียง 🏭

ภาพ: Conveyor belt · Public Domain (CC0 1.0)
for x in collection — ไม่ต้องสร้าง index ก่อน
นอกจากใช้ loop สร้าง index แล้ว Python ยังมี For-loop อีกรูปแบบที่ เข้าถึงข้อมูลได้โดยไม่ต้องสร้าง index
ตัวแปร x ในแต่ละรอบคือ item หรือข้อมูลแต่ละรายการใน collection (เรียงจาก index = 0, 1, 2, …)
หากยังต้องการ index ของข้อมูลแต่ละตัวเพื่อประกอบการแสดงผล ใช้คำสั่ง enumerate()
Note
ทบทวน: enumerate() (Module 7)
คำสั่ง enumerate() จะสร้างรายการ Tuple ของ (index, value) สำหรับแต่ละ item
enumerate() จับคู่ index กับ valueenumerate() จับ ตำแหน่ง (index) มาคู่กับ ค่า (value) แต่ละตัว → for i, x แยกออกเป็น 2 ตัวแปร
🟣 index (0,1,2,…) · 🔵 value — for i, x แตก tuple ออกเป็น 2 ตัวแปรอัตโนมัติ
Warning
Set ไม่รับประกันลำดับ — ผลลัพธ์อาจเรียงต่างจากนี้ และค่าซ้ำ ('Barcelona') จะถูกตัดเหลือตัวเดียว
Note
ทบทวน: Set (Module 4)
สร้าง dictionary person แล้ววน — ตัวแปรในลูปคือ key
Note
ทบทวน: Dictionary (Module 4)
for บน Dictionary ได้อะไรวน for k in person → k เป็น key · อยากได้ value ต้อง person[k] · อยากได้ทั้งคู่ใช้ .items()
List of Dict และ Dict of List
List of Dict คือ List ที่มีสมาชิกเป็น Dictionary
students[1]["height"] — ชั้นแรก index เลือก dict · ชั้นสอง key เลือก value
จาก students แสดงชื่อและความสูงของทุกคน แล้วบอกว่าใครสูงที่สุด
(ชื่อ) is (ความสูง) cm tall.The tallest person in the group is (ชื่อ) with the height of (ความสูง) cm.คิดก่อน: ต้องใช้ตัวแปร “เก็บค่าสูงสุด” และ “เก็บชื่อ” เริ่มต้นเป็นค่าใด?
คำนวณ BMI ของทุกคน แล้วเพิ่ม key 'bmi' เข้าไปในแต่ละ dictionary
\[\mathsf{BMI} = \frac{\text{น้ำหนัก (kg)}}{\left(\dfrac{\text{ส่วนสูง (cm)}}{100}\right)^2}\]
ปัดเป็นทศนิยม 2 ตำแหน่ง
Note
ทบทวน: Arithmetic / ** (Module 3)
Dict of List คือ dictionary ที่มี value เป็น list
จาก persons แสดงชื่อและน้ำหนักของทุกคน แล้วบอกว่าใครหนักที่สุด
(ชื่อ) is (น้ำหนัก) kg.The heaviest person in the group is (ชื่อ) with the weight of (น้ำหนัก) kg.คิดก่อน: น้ำหนักเก็บอยู่ที่ index ใดของ list ที่เป็น value? (["male", 180.5, 80])
ทบทวน Collections
.append() .insert() .remove() .pop() · slice [start:stop:step]tuple() / list()key:value · .pop() .keys() .items()Loop สร้าง index
range(start,stop,step)For-loop เข้าถึงข้อมูลตรง
for x in collection — ได้ item ทีละตัวenumerate() — ได้ (index, value)Collection หลายมิติ
s['key']d[key][index]Tip
loop + condition ช่วยกรอง/นับ/ค้นหาข้อมูลใน collection ได้สะดวก
🏠 259201 — Module 8 | ภาควิชาวิศวกรรมคอมพิวเตอร์ คณะวิศวกรรมศาสตร์ มหาวิทยาลัยเชียงใหม่