Search code examples
pythonarrayslistdictionarystore

Store points by x, y and multiple z


I will write an example so you can understand me :

For instance, I have these 3 points : (0, 1, 244) - (0, 1, 255) - (1, 2, 133)

Actually I need to average the Z when 2 points have the same (x, y). My idea is to store them in something (an array, a dictionary ?) with a double index/key where the value is an array of the Z.

So I basically want to have this : [0, 1, [244, 255]] and [1, 2, [133]]

My problem is I don't know what to use to store them the simpliest way to do so...

Thanks in advance !


Solution

  • Tuples can be dictionary keys:

    myDict = {(1,2): 3}
    

    is perfectly valid.

    Another approach would be to use itertools.groupby, but make sure that your list is already sorted by they key you want to use for your groups (https://docs.python.org/3/library/itertools.html#itertools.groupby):

    from itertools import groupby
    
    myList = [(1,2,3), (1,2,4), (1,3,4)]
    for grp, values in groupby(myList, lambda x: (x[:2])):
       print(grp, list(values))