How to process a date diference using same id elements in a list
<p><strong>I have the following data structure:</strong></p>

<pre><code>[ (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)),
  (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)),
  (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)),
  (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)),
  (80L, datetime.datetime(2014, 9, 15, 14, 16, 39)),
  (80L, datetime.datetime(2014, 2, 6, 8, 58, 39)),
  (80L, datetime.datetime(2014, 9, 8, 14, 21, 48)),
  (90L, datetime.datetime(2016, 8, 2, 18, 14, 31)),
  (90L, datetime.datetime(2016, 8, 2, 21, 14, 23)),
  (90L, datetime.datetime(2014, 1, 5, 16, 35, 34))  ]
</code></pre>

<p>And i need to calculate the average days between the days from users with same id, first element corresponds to user id's and the second one to a datetime.</p>

<p>I'm getting trouble on how to iterate through the list, counting and getting the same diff for each user...</p>

<p>I would sort the timestamps into a dictionary where each key is a user's ID and the value is a list of access times. then after sorting that list of timestamps, find the difference between each visit time and find the average. the <code>datetime.timedelta</code> object can be used to simplify math operations on timestamps..</p>

<pre class="lang-python prettyprint-override"><code>from collections import defaultdict
from datetime import datetime

#l = [(id, datetime), (...), ...]

d = defaultdict(list)
for ID, time in l:
    d[ID].append(time) # build list of times from timestamps
    d[ID].sort() # sorting every time is not optimal but functional

for ID in d.keys():
    timeDeltas = [d[ID][i+1] - d[ID][i] for i in range(len(d[ID])-1)] # create list of timedeltas
    averageVisitFrequency = reduce(lambda x,y: x+y, timeDeltas)//len(timeDeltas) # calculate average timedelta
    print 'user {} makes a purchase every {} days on average'.format(ID, averageVisitFrequency.days) # example output usage</code></pre>

python list loops counting