python字典值求平均值_在python字典中求非零值的平均值

因为你要求的是最快的,这里有一些时间安排。请注意,我在windows8上使用IPython和python3.3,运行i7-3770。另外,在python2.x上,不应该像使用整数除法一样使用/进行除法。请改用float(a)/b,或者在文件顶部添加一个from __future__ import division。在d = {"a": {"pen": 12, "table": 23},

"b": {"pen": 12, "table": 0},

"c": {"pen": 16, "table": 54}}

def method0(): # Your method

count = sum(1 for inner_dict in d if d[inner_dict]["table"] > 0)

total = sum([d[inner_dict]["table"] for inner_dict in d if d[inner_dict]["table"] > 0])

average = total/count

def method1():

count = 0

total = 0

for a in d.values():

val = a['table']

if val > 0:

count += 1

total += val

average = total/ count

def method2(): # user3684792's/Padraic Cunningham's method

filtered = [d[i]["table"] for i in d if d[i]["table"] > 0]

average = sum(filtered)/len(filtered)

# from functools import reduce # If using Python 3

def method3(): # Sylvain Leroux's method

n, s = reduce(lambda acc,v: (acc[0]+1,acc[1]+v["table"]) if v["table"] else acc,

d.values(),

(0, 0))

average = s/n

%timeit method0()

# 10000 loops, best of 3: 23.9 us per loop

%timeit method1()

# 1000000 loops, best of 3: 756 ns per loop

%timeit method2()

# 10000 loops, best of 3: 22.5 us per loop

%timeit method3()

# 1000000 loops, best of 3: 1.29 us per loop

初步结论:使用for循环和简单加法(method1)比本例中的任何列表理解方法都快得多。在

这和你所期望的差不多。请注意,方法1和方法3只迭代一次数据,并在执行过程中收集所有数据。方法0和2迭代更多,因为它们通过一个过程筛选出所需的条目,然后通过另一个过程来求和。在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值