如何使用Python求兩個列表的平均值?


簡介

Python 憑藉其簡潔性和與其他應用程式的靈活互用性而風靡全球。在21世紀,對於資料量龐大的組織來說,資料處理是最具挑戰性的任務之一,而資料科學和機器學習的發展使得資料訪問變得更加容易。列表是一種資料結構,其元素在初始化後是可以改變的。列表通常以有序的形式用方括號“[]”括起來賦值。

使用Python求兩個列表的平均值

在本文中,我們將探討使用Python求兩個列表平均值的各種技術。求平均值的方法包括使用numpy和statistics庫的mean()函式、for迴圈和sum()函式。

語法

sum()  

這是math模組中內建的Python函式,用於對給定數字列表進行求和。

len() 

這也是math模組中的一個函式,它返回給定數字列表的總長度。

mean() 

方法

方法1 - 利用statistics模組

方法2 - 利用lambda函式

方法3 - 利用math模組

方法1:使用statistics模組的Python程式,求兩個列表的平均值

匯入statistics庫,並用三個元素初始化兩個列表。statistics模組中使用的一個函式是mean()函式。然後列印average_of_lists以返回值的列表。

演算法

  • 步驟1 - 需要包含函式的模組是statistics。

  • 步驟2 - 用一組元素初始化兩個列表。

  • 步驟3 - 要求平均值,將兩個元素列表加在一起,然後除以2。

  • 步驟4 - 由於使用了mean()函式,因此不使用求平均值的常規公式。

  • 步驟5 - 列印兩個列表的平均值或均值。

示例

#importing the statistics library
import statistics
# Two list data structures are used to initialize the value.
num_1 = [56, 34, 90]
num_2 = [23, 87, 65]

#statistics module uses the mean function to find the average of two lists
avg_of_lists = statistics.mean(num_1 + num_2)
#returns the average value of the list
print("Mean of the value", avg_of_lists)

輸出

Mean of the value 59.166666666666664

方法2:使用lambda函式的Python程式,求兩個列表的平均值

匯入numpy庫,並用三個元素初始化兩個列表。在函式的情況下,我們使用def函式,但對於匿名函式,我們可以使用lambda函式以及key引數。lambda函式通常與filter()或map()函式一起使用。

演算法

  • 步驟1 - 需要包含函式的模組是numpy。

  • 步驟2 - 用一組元素初始化兩個列表。

  • 步驟3 - 要求平均值,將兩個元素列表加在一起,然後除以2。

  • 步驟4 - 然後使用map()函式以及key引數將其轉換回列表。

  • 步驟5 - 列印兩個列表的平均值或均值。

示例

#importing the numpy library
import numpy as np 
## Two list data structures are used to initialize the value.
num_1 = [56, 34, 90]
num_2 = [23, 87, 65]

#lambda function is used to convert the lists into averages and stores it in the variable avg_value.
avg_value = np.array(list(map(lambda a, b: (a + b) / 2, num_1, num_2)))

#returns the average value of the list
print("Mean of the value", avg_value.mean())

輸出

Mean of the value 59.166666666666664

方法3:使用math模組的Python程式,求兩個列表的平均值

匯入math庫,並用三個元素初始化兩個列表。math模組用於處理計算平均值的正則表示式。然後列印average_of_lists以返回值的列表。

演算法

  • 步驟1 - 包含所需的模組。

  • 步驟2 - 用一組元素初始化兩個列表。

  • 步驟3 - 由於使用了sum()和len()函式,因此不使用求平均值的常規公式。

  • 步驟4 - 列印兩個列表的平均值或均值。

示例

#importing the math library
import math

# Two list data structures are used to initialize the value.
num_1 = [56, 34, 90]
num_2 = [23, 87, 65]
#Regular expression to find the average of two lists
avg_of_lists = (sum(num_1) + sum(num_2)) / (len(num_1) + len(num_2))
#returns the average value of the list
print("Mean of the value", avg_of_lists)

輸出

Mean of the value 59.166666666666664

結論

它對於日常使用者來說非常有用,無論其背景如何,這使得程式設計在準確性、時間和效能方面都更加成功,因此可以在現場專案或學術研究中不受限制地進行類似的實現。

更新於:2023年8月25日

596 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.