Python – 列表中字符串平均长度

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程序主要用于处理数据,比如初始化列表以存储字符串、整数甚至浮点数等值。像数学计算涉及到简单的方法来获取数字的平均值,以上提供的方法返回平均字符串长度。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程