📜  Python - 大于 K 的数字平均值

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

Python - 大于 K 的数字平均值

给定元素列表,提取平均位数大于 K 的元素。

方法 #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]