Python - 巢狀列表的列求和
Python 中的巢狀列表是指包含其他列表作為元素的列表。這是一種在單個列表中建立分層或多維結構的方法。內部列表本身可以包含任何型別的元素,包括其他列表。
處理多維資料(例如矩陣、表格或分層結構)時,巢狀列表非常有用。它們提供了一種靈活且便捷的方式來以結構化的方式組織和訪問資料。讓我們建立一個巢狀列表作為示例。
示例
在這個例子中,我們有一個包含三個內部列表的巢狀列表。每個內部列表代表一行,每個內部列表中的元素代表不同列中的值。
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("The nested list:",nested_list)
輸出
The nested list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
巢狀列表的結構也允許更復雜的資料表示。例如,我們可以為內部列表設定不同的長度,從而建立如下所示的鋸齒狀或不均勻結構。
示例
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print("The nested list with different sizes:",nested_list)
輸出
The nested list with different sizes: [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
在 Python 中,為了計算巢狀列表的列求和,我們可以使用不同的方法。以下是每種方法的詳細解釋以及示例。
使用迴圈
如果我們有一個巢狀列表,其中每個內部列表代表一行,內部列表中的元素代表不同列中的值,我們可以使用迴圈迭代列並計算每列的和。
示例
在這個例子中,我們首先透過訪問第一個內部列表的長度來計算列數`num_columns`。我們用零初始化一個列表`column_sum`來儲存每列的和。然後,我們迭代巢狀列表中的每一行,對於每一行,我們迭代行中元素的索引。我們透過添加當前行中的值來更新`column_sum`中的相應元素。
nested_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
num_columns = len(nested_list[0])
column_sum = [0] * num_columns
for row in nested_list:
for i in range(num_columns):
column_sum[i] += row[i]
print("The column sum of each of the nested lists:",column_sum)
輸出
The column sum of each of the nested lists: [12, 15, 18]
使用`zip()`和列表推導式
我們可以利用zip()函式來轉置巢狀列表,將每一列的值組合在一起。然後,我們可以使用列表推導式來計算每列的和。
示例
在這個例子中,zip(*nested_list)轉置巢狀列表,建立一個迭代器,返回包含每列元素的元組。然後,列表推導式使用sum(column)計算每列的和,得到一個列和的列表。
nested_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
column_sum = [sum(column) for column in zip(*nested_list)]
print("The column sum of each of the nested lists:",column_sum)
輸出
The column sum of each of the nested lists: [12, 15, 18]
使用NumPy
NumPy 是 Python 中用於進行科學和數學計算的最有用的庫之一。NumPy 庫中有一個名為sum()的函式,可以幫助計算巢狀列表的列求和。
示例
在這個例子中,我們使用np.array(nested_list)將巢狀列表轉換為 NumPy 陣列,其中每個內部列表代表陣列中的一行。然後,我們使用np.sum(arr, axis=0)沿第一軸(即行)計算和,從而有效地得到列求和。
import numpy as np
nested_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 10]]
arr = np.array(nested_list)
column_sum = np.sum(arr, axis=0)
print("The column sum of each of the nested lists:",column_sum)
輸出
The column sum of each of the nested lists: [12 15 19]
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP