Is there any pythonic way to find average of specific tuple elements in array?

前端 未结 8 1123
你的背包
你的背包 2021-01-01 11:35

I want to write this code as pythonic. My real array much bigger than this example.

( 5+10+20+3+2 ) / 5

print(np.mean(array,key=lambda x:x[1])

相关标签:
8条回答
  • 2021-01-01 12:28

    With pure Python:

    from operator import itemgetter
    
    acc = 0
    count = 0
    
    for value in map(itemgetter(1), array):
        acc += value
        count += 1
    
    mean = acc / count
    

    An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:

    data = [sub[1] for sub in array]
    mean = sum(data) / len(data)
    

    If you are open to using numpy, I find this cleaner:

    a = np.array(array)
    
    mean = a[:, 1].astype(int).mean()
    
    0 讨论(0)
  • 2021-01-01 12:29

    You can simply use:

    print(sum(tup[1] for tup in array) / len(array))
    

    Or for Python 2:

    print(sum(tup[1] for tup in array) / float(len(array)))
    

    Or little bit more concisely for Python 2:

    from math import fsum
    
    print(fsum(tup[1] for tup in array) / len(array))
    
    0 讨论(0)
提交回复
热议问题