2024年9月30日 星期一

List Comprehension(列表推導式) 範例代碼

 15個不同的 List Comprehension(列表推導式) 範例代碼,涵蓋不同的應用情境:

1. 平方數列表

squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. 偶數列表

evens = [x for x in range(20) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

3. 奇數列表

odds = [x for x in range(20) if x % 2 != 0]
print(odds)  # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

4. 字母大寫轉小寫

lowercase_letters = [char.lower() for char in ['A', 'B', 'C', 'D']]
print(lowercase_letters)  # ['a', 'b', 'c', 'd']

5. 過濾出長度大於3的單詞

words = ['apple', 'bat', 'car', 'elephant']
filtered_words = [word for word in words if len(word) > 3]
print(filtered_words)  # ['apple', 'elephant']

6. 將數字轉為字串

num_strings = [str(num) for num in range(5)]
print(num_strings)  # ['0', '1', '2', '3', '4']

7. 列表中的元素平方再加一

modified_list = [(x**2) + 1 for x in range(5)]
print(modified_list)  # [1, 2, 5, 10, 17]

8. 過濾出負數

numbers = [-10, -5, 0, 5, 10]
negatives = [x for x in numbers if x < 0]
print(negatives)  # [-10, -5]

9. 使用條件來修改列表中的元素

numbers = [1, 2, 3, 4, 5]
modified_numbers = [x*2 if x % 2 == 0 else x*3 for x in numbers]
print(modified_numbers)  # [3, 4, 9, 8, 15]

10. 二維列表生成(乘法表)

multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(multiplication_table)
# [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]

11. 過濾出正數並平方

numbers = [-3, -2, -1, 0, 1, 2, 3]
positive_squares = [x**2 for x in numbers if x > 0]
print(positive_squares)  # [1, 4, 9]

12. 將列表中的字串反轉

words = ['python', 'hello', 'world']
reversed_words = [word[::-1] for word in words]
print(reversed_words)  # ['nohtyp', 'olleh', 'dlrow']

13. 生成0到4的平方列表,但排除平方為4的數字

filtered_squares = [x**2 for x in range(5) if x**2 != 4]
print(filtered_squares)  # [0, 1, 9, 16]

14. 列表中每個字串的長度

words = ['apple', 'banana', 'cherry']
lengths = [len(word) for word in words]
print(lengths)  # [5, 6, 6]

15. 巢狀列表的展平

nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)  # [1, 2, 3, 4, 5, 6]

這些例子涵蓋了不同的List Comprehension應用,包括基本操作、過濾條件、列表生成以及巢狀列表的處理。這些範例將有助於學生加深對列表推導式的理解。

沒有留言:

張貼留言