0

I'm trying to find the average of the values inside of the tuples in this list

[('coinbasepro', 10822.0), ('bitstamp', 10832.82)]

What would be the most pythonic way (like lambdas, reduce, list comprehensions) to do this simple operation?

mert cihan
  • 63
  • 8
  • sum itemgetter len – Kenny Ostrom Jul 02 '19 at 21:16
  • 1
    coding style is not really on-topic for this forum. In general good coding style is about "can the next person who looks at this code quickly and accurately determine what it is accomplishing?" and also "is this code written in a way that the language it is written in can compute the result in a reasonably efficient manner?" Take care to answer those two questions for yourself, and you'll have your answer. – Aaron Jul 02 '19 at 21:16
  • 1
    `statistics.mean(x for _,x in data)` ? – John Coleman Jul 02 '19 at 21:17

2 Answers2

3
import numpy as np
data = [('coinbasepro', 10822.0), ('bitstamp', 10832.82)]
average = np.mean([i[1] for i in data])
amalik2205
  • 3,962
  • 1
  • 15
  • 21
1

Here is one way that doesn't not require any extra packages (assuming your list will always be in this format):

l1 = [('coinbasepro', 10822.0), ('bitstamp', 10832.82)]
nums = [x[1] for x in l1]
avg = sum(nums) / len(nums)

print(avg)
# 10827.41
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43