📜  Python|两个列表的平均值

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

Python|两个列表的平均值

在列表中找到平均值的问题很常见。但有时这个问题可以扩展为两个列表,因此成为一个修改后的问题。本文讨论了可以轻松执行此任务的速记。让我们讨论一些可以解决这个问题的方法。

方法#1:使用sum() + len() + “+” operato
平均值可以通过Python的常规 sum() 和 len函数确定,并且可以使用“+”运算符处理一到两个列表的扩展。

# Python3 code to demonstrate
# Average of two lists
# using sum() + len() + "+" operator
  
# initializing lists
test_list1 = [1, 3, 4, 5, 2, 6]
test_list2 = [3, 4, 8, 3, 10, 1]
  
# printing the original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
  
# Average of two lists
# using sum() + len() + "+" operator
res = sum(test_list1 + test_list2) / len(test_list1 + test_list2)
  
# printing result
print ("The Average of both lists is : " + str(res))
输出 :
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667

方法#2:使用sum() + len() + chain()
执行此特定任务的另一种方法是使用链函数,该函数执行类似于“+”运算符但使用迭代器的任务,因此速度更快。

# Python3 code to demonstrate
# Average of two lists
# using sum() + len() + "+" operator
from itertools import chain
  
# initializing lists
test_list1 = [1, 3, 4, 5, 2, 6]
test_list2 = [3, 4, 8, 3, 10, 1]
  
# printing the original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
  
# Average of two lists
# using sum() + len() + "+" operator
res = sum(chain(test_list1, test_list2)) / len(list(chain(test_list1, test_list2)))
  
# printing result
print ("The Average of both lists is : " + str(res))
输出 :
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667