【问题标题】:Summing travel times with large list in python3在python3中用大列表总结旅行时间
【发布时间】:2017-03-18 22:48:17
【问题描述】:

我有一个非常大的列表 (~2GB),记录了不同地点之间的旅行时间。在每个位置之间列出了多个值,其中一些重复如下:

Raw_Travel_Times=[('AB',2),('BC',5),('AB',8),('BC',10),('BC',7)]

我正在尝试有效地计算每个位置之间的平均旅行时间,例如:

Ave_Travel_Times=[('AB',5),('BC',11)]

我认为使用Counter 是可行的方法,但我想出的最佳解决方案太慢了:

# count how many times each Origin-Destination pair occurs
    Trips=dict(Counter(Travel_Times))

{'AB':2,'BC':3}

# total travel time for each Origin-Destination pair
    CTime=Counter(AB)
    for t in Raw_Travel_Times:
      CTime=CTime+Counter({t[0]:t[1]})

    for c in CTime:
       Link=c
       Total_Time=CTime[c]
       Num_Trips=Trips[c]
       Avetime=TotalTime/Num_Trips
       Ave_Travel_Times.append(Link,Avetime)

必须有一种更有效的方法来做到这一点,但我显然无法看到它。对此的任何帮助将不胜感激。

【问题讨论】:

  • 对于像您这样的庞大且同质的数据,可能值得切换到 numpy。您可能会看到巨大的性能改进,具体取决于您对数据的处理方式。
  • @AndrasDeak 我建议pandas 更适合这项任务。
  • @Denziloe 同意,我第一次回复时没有通读。

标签: python performance python-3.x counter


【解决方案1】:

defaultdict 可能是您所追求的:

location_times = [('AB',2),('BC',5),('AB',8),('BC',10),('BC',7)]

from collections import defaultdict
from statistics import mean

dd = defaultdict(list)

for location, time in location_times:
    dd[location].append(time)

result = {location: mean(times) for location, times in dd.items()}

您也可以学习学习pandas 库的基础知识。

【讨论】:

    【解决方案2】:

    您可以尝试对数据进行一次排序,然后对它们进行一次计算以计算平均值。这需要排序(这是额外的工作),但避免将一百万个项目附加到列表中(这非常慢):

    from itertools import groupby
    from statistics import mean # thanks to @Denziloe
    
    raw_times = [('AB',2),('BC',5),('AB',8),('BC',10),('BC',7)]
    
    def pathgetter(tup):
        return tup[0] # essentially operator.itemgetter(0)
    
    temp_times = sorted(raw_times,key=pathgetter)
    avg_times = [(path,mean((item[1] for item in sublist)))
                 for path,sublist in groupby(temp_times,pathgetter)]
    

    我不知道的statistics.mean 的信用转到@Denziloe

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 1970-01-01
      • 2022-10-15
      • 2022-06-16
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      相关资源
      最近更新 更多