Python - 大于 K 的数字平均值
给定元素列表,提取平均位数大于 K 的元素。
Input : test_list = [633, 719, 8382, 119, 327], K = 5
Output : [719, 8382]
Explanation : (7 + 1 + 9) / 3 = 5.6 and (8 + 3 + 8 + 2) / 4 = 5.2 , both of which are greater than 5, hence returned.
Input : test_list = [633, 719, 8382, 96], K = 5
Output : [719, 8382, 96]
Explanation : All the elements are displayed in output whose digit average is greater than 5.
方法 #1:使用列表推导 + sum() + len()
在这里,我们使用sum()计算数字总和,然后将总和除以元素长度以获得平均值,如果大于 K 则添加结果。
Python3
# Python3 code to demonstrate working of
# Average digit greater than K
# Using sum() + len() + list comprehension
# initializing list
test_list = [633, 719, 8382, 119, 327]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# getting average and checking if greater than K
res = [sub for sub in test_list if sum(
[int(ele) for ele in str(sub)]) / len(str(sub)) >= K]
# printing result
print("Filtered List : " + str(res))
Python3
# Python3 code to demonstrate working of
# Average digit greater than K
# Using sum() + len() + filter() + lambda
# initializing list
test_list = [633, 719, 8382, 119, 327]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# getting average and checking if greater than K
# using filter() and lambda to filter
res = list(filter(lambda sub: sum(
[int(ele) for ele in str(sub)]) / len(str(sub)) >= K, test_list))
# printing result
print("Filtered List : " + str(res))
输出:
The original list is : [633, 719, 8382, 119, 327]
Filtered List : [719, 8382]
方法#2:使用 sum() + len() + filter() + lambda
在这里,过滤操作是使用filter()和lambda来执行的,其余的所有操作都按照上面的方法处理。
蟒蛇3
# Python3 code to demonstrate working of
# Average digit greater than K
# Using sum() + len() + filter() + lambda
# initializing list
test_list = [633, 719, 8382, 119, 327]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# getting average and checking if greater than K
# using filter() and lambda to filter
res = list(filter(lambda sub: sum(
[int(ele) for ele in str(sub)]) / len(str(sub)) >= K, test_list))
# printing result
print("Filtered List : " + str(res))
输出:
The original list is : [633, 719, 8382, 119, 327]
Filtered List : [719, 8382]