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>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> to group by user id (assuming the list is sorted by the grouping key - which looks like it is), then, you can use "pairwise" iteration and calculate an average day difference:</p>

<pre><code>In [1]: import datetime
In [2]: from operator import itemgetter
In [3]: from itertools import groupby, combinations

In [4]: l = [ 
   ...:   (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))  ]

In [5]: for user_id, dates in groupby(l, itemgetter(0)):
    ...:     dates = [date[1] for date in dates]
    ...:     differences = [abs((d1 - d2).days) for d1, d2 in zip(dates[0::2], dates[1::2])]
    ...:     print(user_id, sum(differences) / len(differences))
    ...:     
(19L, 2)
(80L, 108)
(90L, 1)
</code></pre>

python list loops counting