On this page
วันที่ 13 — List Comprehension
เรียนรู้ List Comprehension วิธีสร้าง list แบบกระชับและมีประสิทธิภาพ พร้อม Lambda Function สำหรับฟังก์ชันนิรนาม
List Comprehension
List comprehension ใน Python คือวิธีกระชับในการสร้าง list จาก sequence เป็นวิธีที่เร็วกว่าการประมวลผล list ด้วย for loop มาก:
# syntax
[expression for i in iterable if condition]ตัวอย่างที่ 1 — แปลง string เป็น list ของตัวอักษร:
# One way
language = 'Python'
lst = list(language) # changing the string to list
print(type(lst)) # list
print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
# Second way: list comprehension
lst = [i for i in language]
print(type(lst)) # list
print(lst) # ['P', 'y', 't', 'h', 'o', 'n']ตัวอย่างที่ 2 — สร้าง list ของตัวเลข:
# Generating numbers
numbers = [i for i in range(11)] # to generate numbers from 0 to 10
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# It is possible to do mathematical operations during iteration
squares = [i * i for i in range(11)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# It is also possible to make a list of tuples
numbers = [(i, i * i) for i in range(11)]
print(numbers) # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]ตัวอย่างที่ 3 — List comprehension กับ if expression:
# Generating even numbers
even_numbers = [i for i in range(21) if i % 2 == 0] # to generate even numbers list in range 0 to 21
print(even_numbers) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Generating odd numbers
odd_numbers = [i for i in range(21) if i % 2 != 0] # to generate odd numbers in range 0 to 21
print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Filter numbers: let's filter out positive even numbers from the list below
numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10]
positive_even_numbers = [i for i in numbers if i % 2 == 0 and i > 0]
print(positive_even_numbers) # [4, 6, 8, 10]
# Flattening a two dimensional array
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [ number for row in list_of_lists for number in row]
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]Lambda Function
Lambda function คือ function นิรนามขนาดเล็กที่ไม่มีชื่อ รับ arguments ได้หลายตัวแต่มี expression ได้แค่ตัวเดียว คล้ายกับ anonymous functions ใน JavaScript ใช้เมื่อต้องการเขียน anonymous function ภายใน function อื่น
การสร้าง Lambda Function
ใช้ keyword lambda ตามด้วย parameter(s) และ expression Lambda function ไม่ใช้ return แต่จะ return expression โดยอัตโนมัติ:
# syntax
x = lambda param1, param2, param3: param1 + param2 + param3
print(x(arg1, arg2, arg3))# Named function
def add_two_nums(a, b):
return a + b
print(add_two_nums(2, 3)) # 5
# Lets change the above function to a lambda function
add_two_nums = lambda a, b: a + b
print(add_two_nums(2,3)) # 5
# Self invoking lambda function
(lambda a, b: a + b)(2,3) # 5 - need to encapsulate it in print() to see the result in the console
square = lambda x : x ** 2
print(square(3)) # 9
cube = lambda x : x ** 3
print(cube(3)) # 27
# Multiple variables
multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c
print(multiple_variable(5, 5, 3)) # 22Lambda Function ภายใน Function อื่น
การใช้ lambda function ภายใน function อื่น:
def power(x):
return lambda n : x ** n
cube = power(2)(3) # function power now need 2 arguments to run, in separate rounded brackets
print(cube) # 8
two_power_of_five = power(2)(5)
print(two_power_of_five) # 32💻 แบบฝึกหัด — วันที่ 13
- กรองเฉพาะตัวเลขติดลบและศูนย์ใน list ต่อไปนี้โดยใช้ list comprehension:
numbers = [-4, -3, -2, -1, 0, 2, 4, 6]- Flatten list ต่อไปนี้เป็น list แบบ one dimensional:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output
[1, 2, 3, 4, 5, 6, 7, 8, 9]- ใช้ list comprehension สร้าง list ของ tuples ต่อไปนี้:
[(0, 1, 0, 0, 0, 0, 0),
(1, 1, 1, 1, 1, 1, 1),
(2, 1, 2, 4, 8, 16, 32),
(3, 1, 3, 9, 27, 81, 243),
(4, 1, 4, 16, 64, 256, 1024),
(5, 1, 5, 25, 125, 625, 3125),
(6, 1, 6, 36, 216, 1296, 7776),
(7, 1, 7, 49, 343, 2401, 16807),
(8, 1, 8, 64, 512, 4096, 32768),
(9, 1, 9, 81, 729, 6561, 59049),
(10, 1, 10, 100, 1000, 10000, 100000)]- Flatten list ต่อไปนี้เป็น list ใหม่:
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
output:
[['FINLAND','FIN', 'HELSINKI'], ['SWEDEN', 'SWE', 'STOCKHOLM'], ['NORWAY', 'NOR', 'OSLO']]- เปลี่ยน list ต่อไปนี้เป็น list ของ dictionaries:
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
output:
[{'country': 'FINLAND', 'city': 'HELSINKI'},
{'country': 'SWEDEN', 'city': 'STOCKHOLM'},
{'country': 'NORWAY', 'city': 'OSLO'}]- เปลี่ยน list of lists ต่อไปนี้เป็น list ของสตริงที่ต่อกัน:
names = [[('Asabeneh', 'Yetayeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]]
output
['Asabeneh Yetaeyeh', 'David Smith', 'Donald Trump', 'Bill Gates']- เขียน lambda function ที่แก้ slope หรือ y-intercept ของ linear functions