Python巢狀列表推導式
巢狀列表是在列表中包含列表。Python 提供了優雅地處理巢狀列表並應用常用函式來操作巢狀列表的功能。在本文中,我們將學習如何使用列表推導式在 Python 中建立和使用巢狀列表。
建立矩陣
建立矩陣涉及建立一系列行和列。我們可以使用 for 迴圈來建立矩陣的行和列,方法是在另一個包含 for 迴圈的 Python 列表內放置一個 Python 列表。
示例
matrix = [[m for m in range(4)] for n in range(3)] print(matrix)
執行以上程式碼,得到以下結果
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
從巢狀列表中過濾
我們可以使用帶有過濾功能的列表推導式,方法是在子列表中使用 for 迴圈。下面我們有一個二維列表,在一個更大的列表內包含一層子列表。我們訪問這些巢狀列表中的每個元素。透過使用過濾器條件。
示例
years = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August', 'September'],['October','November','December']] # Nested List comprehension with an if condition years = [years for sublist in years for years in sublist if len(years) <= 5] print(years)
執行以上程式碼,得到以下結果
['March', 'April', 'May', 'June', 'July']
展平巢狀子列表
我們還可以獲取一個巢狀列表並將其展平,方法是建立一個不包含任何子列表的單個列表。
示例
nested_list = [[1] ,[17, 19], [21,23,25], [32,35,37,39]] # Nested List Comprehension to flatten a given 2-D matrix flattened_list = [value for sublist in nested_list for value in sublist] print(flattened_list)
執行以上程式碼,得到以下結果
[1, 17, 19, 21, 23, 25, 32, 35, 37, 39]
廣告