w3resource

Python: Calculate the average value of the numbers in a given tuple of tuples using lambda

Python Lambda: Exercise-44 with Solution

Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.

Sample Solution:

Python Code :

# Define a function 'average_tuple' that calculates the average of elements in a tuple of tuples
def average_tuple(nums):
    # Use 'zip(*nums)' to unpack the tuples in 'nums' and then apply 'map' with a lambda to calculate the averages
    # For each position (index) in the unpacked tuples, calculate the average of elements at that position across tuples
    # Convert the averages into a tuple
    result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
    
    # Return the tuple of average values
    return result

# Create a tuple of tuples 'nums' containing integer values
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))

# Print the original tuple 'nums' and the average value of numbers in the tuple of tuples using 'average_tuple' function
print("Original Tuple:")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n", average_tuple(nums))

# Create another tuple of tuples 'nums' containing integer values including negative numbers
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))

# Print the original tuple 'nums' and the average value of numbers in the tuple of tuples using 'average_tuple' function
print("\nOriginal Tuple:")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n", average_tuple(nums)) 

Sample Output:

Original Tuple: 
((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))

Average value of the numbers of the said tuple of tuples:
 (30.5, 34.25, 27.0)

Original Tuple: 
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))

Average value of the numbers of the said tuple of tuples:
 (25.5, -18.0, 3.75)

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to multiply all the numbers in a given list using lambda.
Next: Write a Python program to convert string element to integer inside a given tuple using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/lambda/python-lambda-exercise-44.php