📜  Python - 列表中的平均数字数

📅  最后修改于: 2022-05-13 01:54:30.452000             🧑  作者: Mango

Python - 列表中的平均数字数

给定一个元素列表,提取 List 中的平均数字数。

方法 #1:使用len() + loop + str()

在此,我们迭代每个元素,转换为字符串,并找到它的长度,使用计数器进行求和,然后将结果与列表中的总元素相除得到结果。

Python3
# Python3 code to demonstrate working of 
# Average digits count
# Using len() + loop + str()
  
# initializing list
test_list = [34, 2345, 23, 456, 2, 23, 456787]
  
# printing original list
print("The original list is : " + str(test_list))
  
sumd = 0
for ele in test_list:
      
    # summing digits length 
    sumd += len(str(ele))
  
# getting result after dividing total digits by elements    
res = sumd / len(test_list)
  
# printing result 
print("Average digits length : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Average digits count
# Using len() + sum() + str()
  
# initializing list
test_list = [34, 2345, 23, 456, 2, 23, 456787]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting summation and dividing by total length
res = sum([len(str(ele)) for ele in test_list]) / len(test_list)
  
# printing result 
print("Average digits length " + str(res))


输出
The original list is : [34, 2345, 23, 456, 2, 23, 456787]
Average digits length : 2.857142857142857

方法 #2:使用 len() + sum() + str()

在这种情况下,求和的任务是使用 sum() 完成的,扩展了解决问题的紧凑方法。

蟒蛇3

# Python3 code to demonstrate working of 
# Average digits count
# Using len() + sum() + str()
  
# initializing list
test_list = [34, 2345, 23, 456, 2, 23, 456787]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting summation and dividing by total length
res = sum([len(str(ele)) for ele in test_list]) / len(test_list)
  
# printing result 
print("Average digits length " + str(res))
输出
The original list is : [34, 2345, 23, 456, 2, 23, 456787]
Average digits length 2.857142857142857