Python - 计算列表中正元素的百分比
给定一个列表,计算列表中正元素的百分比。
Input : test_list = [4, 6, -2, 3, -8, -9, -1, 8, 9, 1]
Output : 60.0
Explanation : 6/10 elements are positive.
Input : test_list = [-4, 6, -2, 3, -8, -9, -1, 8, 9, 1]
Output : 50.0
Explanation : 5/10 elements are positive.
方法 #1:使用len() +列表理解
在此,我们使用列表推导构建正元素列表,然后使用 len() 计算列表的长度,将两个长度除以并乘以 100 以获得百分比计数。
Python3
# Python3 code to demonstrate working of
# Positive values percentage
# Using len() + list comprehension
# initializing list
test_list = [4, 6, -2, 3, -8, 0, -1, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# getting filtered list using comprehension and
# division to get fraction
res = (len([ele for ele in test_list if ele > 0]) / len(test_list)) * 100
# printing result
print("Positive elements percentage : " + str(res))
Python3
# Python3 code to demonstrate working of
# Positive values percentage
# Using filter() + lambda + len()
# initializing list
test_list = [4, 6, -2, 3, -8, 0, -1, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# getting filtered list using filter(), lambda and
# division to get fraction
res = (len(list(filter(lambda ele: ele > 0, test_list))) / len(test_list)) * 100
# printing result
print("Positive elements percentage : " + str(res))
输出:
The original list is : [4, 6, -2, 3, -8, 0, -1, 8, 9, 1]
Positive elements percentage : 60.0
方法 #2:使用filter() + lambda + len()
在此,我们使用 filter() 和 lambda 执行获取正元素的任务,其余所有任务都执行类似于上述方法。
蟒蛇3
# Python3 code to demonstrate working of
# Positive values percentage
# Using filter() + lambda + len()
# initializing list
test_list = [4, 6, -2, 3, -8, 0, -1, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# getting filtered list using filter(), lambda and
# division to get fraction
res = (len(list(filter(lambda ele: ele > 0, test_list))) / len(test_list)) * 100
# printing result
print("Positive elements percentage : " + str(res))
输出:
The original list is : [4, 6, -2, 3, -8, 0, -1, 8, 9, 1]
Positive elements percentage : 60.0