Siii
Siii

Reputation: 483

Sorting and grouping lists and sub lists with the same values in Python

I'm wondering can anyone help me with this problem, I feel so close yet so far.... I can't seem to get my head around this.

I have a list of 3D vectors (X,Y,Z) to be sorted by columns - many of the X values are the same.

# Example list (L)

L = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]

# Desired result
R = [[1,7,9], [1,12,9]], [[2,4,9], [2,0,10]],[[4,6,2], [4,12,6]], [5,7,1], [7,6,2], [9,9,1]

# Example calling individual columns (real values expected to be in the 10's)

R[0] = [[1,7,9], [1,12,9]] # A column 2 high
R[3] = [5,7,1] # A column 1 high

Working example on a single list

Using the Counter function in the collections module and with some much appreciated help on here, the following code can sort a single list:

 from collections import Counter

 N = [2,5,7,9,2,8,5,2,7,9]
 C = Counter(N)

 print [ [k,]*v for k,v in C.items()]
 # Returns [[8], [9, 9], [2, 2, 2], [5, 5], [7, 7]]

I tried linking the Y and Z values back to newly grouped X vectors, however I ran into indexing issues, as the indices of X list changed.

Any help on this would be much appreciated, so far this is my attempt and the direction I'm exploring... (passing values into functions)

from collections import Counter

N = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]


def compareXvalues(VectorList):
    global Grouped_X_Vectors

    Xvectors = []
    for i in xrange (len(VectorList)):
       Xvectors.append(VectorList[i][0])

    C = Counter(Xvectors)
    Grouped_X_Vectors = [ [k,]*v for k,v in C.items()]

    for i in xrange (len(Grouped_X_Vectors)):
        #print Grouped_X_Vectors[i]
        pass

print N

compareXvalues(N)
print Grouped_X_Vectors

Any feedback or help would be much appreciated, my brain is fried.

Upvotes: 2

Views: 57

Answers (1)

Brian
Brian

Reputation: 3131

You can accumulate them by X value in a dictionary and then sort the results into a list. In my example I use a defaultdict since I want to call append on the items of the dictionary and this prevents me from needing to initialize a list for each value of X that I encounter.

>>> from collections import defaultdict
>>> L = [[1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]]
>>> d = defaultdict(list)
>>> for item in L:
        d[item[0]].append(item)

>>> R = sorted(d[x] for x in d)
>>> R
[[[1, 7, 9], [1, 12, 9]], [[2, 4, 9], [2, 0, 10]], [[4, 6, 2], [4, 12, 6]], [[5, 7, 1]], [[7, 6, 2]], [[9, 9, 1]]]

I know this is a bit different from the path you were taking, but the dictionary fulfills the basic idea you had of "linking" your Y and Z values to your X value.

Upvotes: 3

Related Questions