Python Subtract Arrays Based on Same Time -


is there way can subtract 2 arrays, making sure subtracting elements have same day, hour, year, , or minute values?

list1 = [[10, '2013-06-18'],[20, '2013-06-19'], [50, '2013-06-23'], [15, '2013-06-30']] list2 = [[5, '2013-06-18'], [5, '2013-06-23'] [20, '2013-06-25'], [20, '2013-06-30']] 

looking for:

 list1-list2 = [[5, '2013-06-18'], [45, '2013-06-23'] [10, '2013-06-30']] 

how using defaultdict of lists?

import itertools operator import sub collections import defaultdict  def subtract_lists(l1, l2):     data = defaultdict(list)     sublist in itertools.chain(l1, l2):         value, date = sublist         data[date].append(value)     return [(reduce(sub, v), k) k, v in data.items() if len(v) > 1]  list1 = [[10, '2013-06-18'],[20, '2013-06-19'], [50, '2013-06-23'], [15, '2013-06-30']] list2 = [[5, '2013-06-18'], [5, '2013-06-23'], [20, '2013-06-25'], [20, '2013-06-30']]  >>> subtract_lists(list1, list2) [(-5, '2013-06-30'), (45, '2013-06-23'), (5, '2013-06-18')] >>> # if want them sorted date... >>> sorted(subtract_lists(list1, list2), key=lambda t: t[1]) [(5, '2013-06-18'), (45, '2013-06-23'), (-5, '2013-06-30')] 

note difference date 2013-06-30 -5, not +5.

this works using date dictionary key list of values given date. lists having more 1 value in list selected, , values in lists reduced subtraction. if want resulting list sorted, can using sorted() date item key. move operation subtract_lists() function if want behavior.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -