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 :

def average_tuple(nums):
    result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
    return result

nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print ("Original Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums))
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
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)

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


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 Python skills with w3resource's quiz



Python: Tips of the Day

Splits values into two groups. If an element in filter is True, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group

Example:

def tips_bifurcate(lst, filter):
  return [
    [x for i, x in enumerate(lst) if filter[i] == True],
    [x for i, x in enumerate(lst) if filter[i] == False]
  ]

print(tips_bifurcate(['little', 'boo', 'peep', 'sat'], [True, True, False, True]))

Output:

[['little', 'boo', 'sat'], ['peep']]