Python | Column Average in Record List

Sometimes the data that we receive, is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the finding average of each index of tuple for cumulation. Let’s discuss certain ways in which this can be performed.

Method #1 : Using list comprehension
This is the most naive method to perform this particular task, in this method we compute the average of each index of all the possible indices of the tuple.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Column Average in Record List
# using list comprehension
  
# initializing list 
test_list = [(1, 6), (3, 4), (5, 8)]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# Column Average in Record List
# using list comprehension
temp = sum(i[0] for i in test_list), sum(i[1] for i in test_list)
res = []
for ele in temp:
    res.append(ele / len(test_list))
  
# printing summation
print ("The position Average of tuples : " + str(res))

chevron_right


Output :



The original list is : [(1, 6), (3, 4), (5, 8)]
The position Average of tuples : [3.0, 6.0]

 

Method #2 : Using zip() + sum()
This is the most elegant and pythonic way to perform this particular task. In this we combine all the indices of the element using zip() and the performance of summation using sum function. And then divide the list by list length to compute average.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Column Average in Record List
# using zip() + sum()
  
# initializing list 
test_list = [(1, 6), (3, 4), (5, 8)]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# Column Average in Record List
# using zip() + sum()
temp = [sum(i) for i in zip(*test_list)]
res = []
for ele in temp:
    res.append(ele / len(test_list))
  
# printing summation
print ("The position Average of tuples : " + str(res))

chevron_right


Output :

The original list is : [(1, 6), (3, 4), (5, 8)]
The position Average of tuples : [3.0, 6.0]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.