Python – 列表中字串的平均長度


Python語言由各種資料結構組成,其中之一是列表資料結構,它可以在方括號記憶體儲不同資料型別元素。每個單詞或字元的長度都會新增到列表的總長度中。列表中每個字串的長度可以用整數、浮點數和字串的組合初始化。之後,將給出的每個字元或數字加起來,然後除以列表的長度。獲取平均字串長度的方法需要遵循某些函式。

字串中的平均字串長度

用於查詢平均字串長度的方法包括使用statistics庫中的mean()函式、map()函式、for迴圈和sum()函式。

方法

方法1 - 使用mean()函式

方法2 - 使用for迴圈

方法3 - 使用map()和sum()函式

方法1:使用statistics模組中的mean()函式查詢平均字串長度的Python程式

該庫用於在functools模組中新增reduce()函式。列表中的字串初始化為list1。使用lambda函式計算列表中每個字串的長度,該函式新增到累加器變數中。此累加器變數最初設定為0。平均值以十進位制數的形式列印。

演算法

  • 步驟1 - 匯入functools庫以使用特定函式計算平均值。

  • 步驟2 - 使用字串和整數值初始化list1。

  • 步驟3 - reduce函式主要用於在名為lambda函式的匿名函式的幫助下減少元素。

  • 步驟4 - 最後,列印列表值。

示例

#import the functools library
from functools import reduce

#initializing the list1 with integers and letters as strings within quotes 
list1 = ["Sharpener", "book", "notepad", "pencil"]

#calculating the length of each word of the string using the reduce function to get the average string length 
list_len = reduce(lambda m, n: m + len(n), list1, 0)

#to get the average of the string length by dividing the list_len by the length of the list1
avg_len = list_len / len(list1)

#printing the string length 
print("Average string length:", avg_len)

輸出

Average string length: 6.5

方法2:使用for迴圈查詢平均字串長度的Python程式

列表中的字串初始化為list1。為了獲得平均值,將字串的長度相加,然後除以字串的數量。返回或列印相應的結果。

演算法

  • 步驟1 - 使用字串值初始化list1,並宣告一個空字串。

  • 步驟2 - 使用迴圈語句迭代列表資料結構。

  • 步驟3 - len函式根據列表中給定的字元計算長度。

  • 步驟4 - 可以實現查詢平均值的公式來獲得結果。

示例

#initializes the input 
list1 = ["Sharpener", "book", "notepad", "pencil"]
#declaring the list as empty
list_len = 0
for charac in list1:
	list_len += len(charac)
#mean value is calculated by dividing the list by the length
avg_len = list_len/len(list1)
#returns the result
print(" List mean can be calculated as: ", avg_len)

輸出

List mean can be calculated as: 6.5

方法3:使用map方法計算列表平均字串長度的Python程式

宣告列表以儲存不同型別的數值。map是最常用的函式之一,用於匹配給定列表中的字串引數。

演算法

  • 步驟1 - 輸入可以根據使用者的需要宣告任何元素。

  • 步驟2 - 將元素新增到列表中,然後除以列表的長度。

  • 步驟3 - 所以最終它返回結果。

示例

#declaring the input
num = ["book", "notepad", "pencil"] 
#map function to find the average 
len1 = sum(map(len, num))
#To get the average length of the string
avglen = len1/len(num)
#to print the result
print("Average string length : ", avglen)

輸出

Average string length: 5.666666666666667

結論

Python程式主要用於處理資料,例如初始化列表以儲存字串、整數甚至浮點數等值。像數學計算一樣,它涉及一種簡單的方法來獲得數字的平均值,並且上面提供的方法返回平均字串長度。

更新於:2023年8月29日

417 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.