Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Comprehensions ใน Python: List, Dict, Set, Generator

Comprehensions เป็นไวยากรณ์เฉพาะของ Python สำหรับสร้าง Sequence ต่างๆ (List, Dictionary, Set, Generator) แบบกระชับและอ่านง่าย เป็นลายลักษณ์อักษรเฉพาะตัว (Idiomatic) ของ Python

1. List Comprehension

ก) ใช้ for loop ธรรมดา

listA = []
for n in range(4, 9):
    listA.append(n ** 3)
print("List using for loop:\n", listA)
List using for loop: [64, 125, 216, 343, 512]

ข) ใช้ List Comprehension (แนะนำ)

listA = [12, 9, 32, 45]
new_list = [n for n in listA if n % 3 == 0]
print("New List:\n", new_list)
New List: [12, 9, 45]

2. Dictionary Comprehension

ก) ใช้ for loop + zip

Day = ['Mon', 'Tue', 'Wed']
Time = ['2pm', '10am', '11am']
dictA = {}
for key, value in zip(Day, Time):
    dictA[key] = value
print("Dictionary using for loop:\n", dictA)
Dictionary using for loop: {'Mon': '2pm', 'Tue': '10am', 'Wed': '11am'}

ข) ใช้ Dict Comprehension

listA = [3, 5, 4, 8, 9, 2]
dictA = {key: key ** 3 for key in listA if key % 2 != 0}
print("Dictionary using comprehension:\n", dictA)
Dictionary using comprehension: {3: 27, 5: 125, 9: 729}

3. Set Comprehension

Set เก็บค่าไม่ซ้ำกัน สร้างได้คล้าย List แต่ใช้ {}

ก) ใช้ for loop + add

listA = [12, 4, 25, 12, 4, 9]
setA = set()
for x in listA:
    if x % 3 == 0:
        setA.add(x)
print("Set using for loop:", setA)
Set using for loop: {9, 12}

ข) ใช้ Set Comprehension

listA = [12, 4, 25, 12, 4, 9]
setA = {x for x in listA if x % 2 == 0}
print("Set using comprehension:", setA)
Set using comprehension: {12, 4}

4. Generator Comprehension

ใช้วงเล็บ () แทน [] สร้าง Generator object ที่คืนค่าทีละตัว (Lazy evaluation) ประหยัดหน่วยความจำ

ตัวอย่าง

listA = [12, 4, 25, 12, 4, 9]
genrtr = (var for var in listA if var % 2 == 0)
print("Values using generator comprehension:")
for x in genrtr:
    print(x, end=',')

ผลลัพธ์

Values using generator comprehension: 12,4,12,4,

สรุป: Comprehensions ทำให้โค้ดสั้น กระชับ และ "Pythonic" มากขึ้น ควรใช้แทน for loop + append/get/add เมื่อเป็นไปได้