Python——資料元組列和
Python 具有豐富且大量的各種函式和庫,使得其在資料分析中十分流行。有時,我們的分析可能需要對一組資料元組的某個列中的值進行求和操作。所以,本程式會將一系列資料元組中同一位置或同一列的所有值進行加和。
以下列舉幾種實現方法。
使用 for 迴圈和 zip
使用 for 迴圈遍歷每一項,然後使用 zip 函式收集每一列中的值。隨後,我們使用求和函式並最終將結果作為新的資料元組。
示例
data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuples: " + str(data))
# using list comprehension + zip()
result = [tuple(sum(m) for m in zip(*n))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))輸出
執行以上程式碼將產生以下結果
The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
使用對映和 zip
我們可以使用對映函式而非 for 迴圈實現相同的結果。
示例
data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuple values: " + str(data))
# using zip() + map()
result = [tuple(map(sum, zip(*n)))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))輸出
執行以上程式碼將產生以下結果
The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP