用 python3 中的大列表总结旅行时间

Summing travel times with large list in python3

我有一个非常大的列表 (~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)

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

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 库的基础知识。

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

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 归功于