Python - 列表中的平均数字数
给定一个元素列表,提取 List 中的平均数字数。
Input : test_list = [34, 2345, 23, 456, 2, 23, 456787]
Output : 2.857142857142857
Explanation : Average of all digit count. [2+4+2+3+1+2+6 = 20, 20/7 = 2.857142857142857]
Input : test_list = [34, 1, 456]
Output : 2.0
Explanation : Average of all digit count. [1 + 2 + 3 = 6, 6 / 3 = 2]
方法 #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