numpy帮助查找时间总和

numpy帮助查找时间总和

我有以下清单,

Events = [0, 0, 0, 1, 1, 0]
Details = ['Start', 'End', 'Start', 'Start', 'End', 'End]
Time = [0, 1, 4, 5, 10, 16]

我需要按以下方式对单个事件进行分组:
Event 0:
Sum of Start Times = 0+4 = 4
Sum of End Times = 1+16 = 17
Total time spend by event 0 = 17-4 = 13

Event 1:
Sum of start times = 5
Sum of end times = 10
Total time spend by event 1 = 10-5=5

我要一些速记本。当有大量的事件和大量的计时时,定义if循环语法就变得很费时了,就像在Java中那样。
有什么有效的方法可以做到这一点吗?

最佳答案

作为一个选项,您可以执行以下操作:

result = {}
for e, d, t in zip(Events, Details, Time):
    result.setdefault(e, {})
    result[e].setdefault(d, 0)
    result[e][d] += t

print result
>>> {0: {'Start': 4, 'End': 17}, 1: {'Start': 5, 'End': 10}}

在那之后,很容易产生你所期望的输出。
更新:
感谢@abarnert:
从集合导入计数器
result = {}
for e, d, t in zip(Events, Details, Time):
    result.setdefault(e, collections.Counter())[d] += t
print result
>>> {0: Counter({'End': 17, 'Start': 4}), 1: Counter({'End': 10, 'Start': 5})}

感谢@AMacK:
result = {}
for e, d, t in zip(Events, Details, Time):
    result.setdefault(e, {}).setdefault(d, []).append(t)

print result
>>> {0: {'Start': [0, 4], 'End': [1, 16]}, 1: {'Start': [5], 'End': [10]}}

谨致问候,
阿尔乔姆

关于python - python lambda,numpy帮助查找时间总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25987504/

10-11 23:23