共計 620 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 嵌套列表的輸出方法有多種,取決于輸出的格式和需求。以下是一些常見的方法:
-
使用循環:
- 使用嵌套的 for 循環遍歷列表的每個元素,并使用 print 語句輸出每個元素。
- 示例代碼:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for sublist in nested_list: for item in sublist: print(item, end=' ') print()
-
使用列表推導式:
- 使用嵌套的列表推導式將嵌套列表展開,并用 print 語句輸出。
- 示例代碼:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened_list = [item for sublist in nested_list for item in sublist] print(flattened_list)
-
使用遞歸:
- 編寫一個遞歸函數,用于遍歷嵌套列表并輸出每個元素。
- 示例代碼:
def print_nested_list(nested_list): for item in nested_list: if isinstance(item, list): print_nested_list(item) else: print(item) nested_list = [[1, 2, 3], [4, [5, 6]], [7, 8, 9]] print_nested_list(nested_list)
這些方法可以根據具體的需求選擇使用。
丸趣 TV 網 – 提供最優質的資源集合!
正文完