Search code examples
pythonlistdictionarylist-comprehensionsublist

grouping values in a list and storing them as sub list


I am working on a problem related to coordinate systems.

This is sample data. The keys in my dictionary represent the x-coordinate and the values in the dictionary represent the y coordinate with respect to the x-coordinate.

data = {0:[1,2,10,35,36,42], 1:[50,55,60,80,85,110]}

I want to preprocess my data in such a way that if two consecutive y-coordinates share a common difference (in this case less than or equal to 10), then a sublist must be created, and all those y-coordinates should be grouped together.

For better understanding, the output should look like this.

output_data = {0:[[1,2,10],[35,36,42]], 1:[[50,55,60],[80,85],[110]]}

Can anyone please provide a solution to my problem?


Solution

  • Something like the below. The idea is to loop over the values, look back and calculate the delta.

    from collections import defaultdict
    DELTA = 10
    data = {0:[1,2,10,35,36,42], 1:[50,55,60,80,85,110]}
    result = defaultdict(list)
    for k,v in data.items():
      temp = [v[0]]
      for idx,x in enumerate(v):
          if idx > 0:
            delta_found = x - temp[-1] > DELTA
            if delta_found :
              result[k].append(temp)
              temp = [x]
            else:
              temp.append(x)
      result[k].append(temp)
    print(result)
    

    output

    defaultdict(<class 'list'>, {0: [[1, 2, 10], [35, 36, 42]], 1: [[50, 55, 60], [80, 85], [110]]})