Python – 第 K 个索引元组列表均值
有时,在使用Python元组时,我们可能会遇到需要计算列表中任何特定元组索引的平均值的问题。这类问题可以应用在数据领域,例如 Web 开发。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(‘Gfg’, 1), (‘is’, 5), (‘best’, 7)], K = 1
Output : 4.333333333333333
Input : test_list = [(‘Gfg’, 7), (‘best’, 7)], K = 1
Output : 7
方法 #1:使用 mean() + 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用 mean() 执行均值计算任务,生成器表达式用于迭代。
Python3
# Python3 code to demonstrate working of
# Kth Index Tuple List Mean
# Using mean() + generator expression
from statistics import mean
# initializing list
test_list = [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# Kth Index Tuple List Mean
# Using mean() + generator expression
res = mean(val[K] for val in test_list)
# printing result
print("The computed mean : " + str(res))
Python3
# Python3 code to demonstrate working of
# Kth Index Tuple List Mean
# Using sum() + len() + generator expression
from statistics import mean
# initializing list
test_list = [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# Kth Index Tuple List Mean
# Using sum() + len() + generator expression
res = sum(val[K] for val in test_list) / len(test_list)
# printing result
print("The computed mean : " + str(res))
输出 :
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6
方法 #2:使用 sum() + len() + 生成器表达式
上述功能的组合也可以用来解决这个任务。在此,我们使用 sum() 执行求和计算任务,结果除以使用 len() 计算的列表长度。
Python3
# Python3 code to demonstrate working of
# Kth Index Tuple List Mean
# Using sum() + len() + generator expression
from statistics import mean
# initializing list
test_list = [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# Kth Index Tuple List Mean
# Using sum() + len() + generator expression
res = sum(val[K] for val in test_list) / len(test_list)
# printing result
print("The computed mean : " + str(res))
输出 :
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6.0