Python List Matrix : Adding Elements / list of index of duplicates in List

Viewed 42

My question is more a why can't I than a how to do, so it's just if you have time for sharing knowledge. I've reduce the problem so now it looks like a find duplicates but that's not what it is about since it's very well documented everywhere.
My question is about why the Method1 isn't valid.
I'm certainly too close to see the obvious so maybe fresh eyes can. The result attended is the list of list of index of similar sorted items, but repeating myself it's not about the result it's about the why Method1 can't produce the result since after iteration 4 n seem to be considered only if > 1

Thanks for your time

...
List1 = ['A4','A2','A3','A1','A4','A4','A2','A3','A1','A4']
print( List1 )
print('-Method1 doesn\'t work--------------')
List2 = []
for i in range( len( List1 ) ) : 
    x = [ List1[ i ], i ]
    List2.append( x )
List2.sort()
print(List2)
n = 0
List3 = [ [ List2[ 0 ][ 1 ] ] ]
for i in range( 1, len( List2 ) ) : 
    if List2[ i ][ 0 ] == List2[ n ][ 0 ] :     
        List3[ n ].append( List2[ i ][ 1 ] )        
    else :
        List3.append( [ List2[ i ][ 1 ] ] )
        n += 1
print( List3 )
print('-Method2 works------------------')
List4 = [ [ 0 ] ]
for i in range( 1, len( List1 ) ):
    if List1[ i ] < List1[ List4[ 0 ][ 0 ] ]:
        List4.insert( 0, [ i ])
    else :
        for j in range( len( List4 ) ):
            if List1[ i ] == List1[ List4[ j ][ 0 ]] :
                List4[ j ].append( i )
                break 
            else : 
                try :
                    if ( List1[ i ] > List1[ List4[ j ][ 0 ] ] ) and (List1[ i ] < List1[ List4[ j+1 ][ 0 ] ]) : 
                        List4.insert( j+1 ,[ i ] )
                        break                     
                except :
                    List4.append( [ i ] )
print( List4 )
...

result

...
['A4', 'A2', 'A3', 'A1', 'A4', 'A4', 'A2', 'A3', 'A1', 'A4']
-Method1 doesn't work
[['A1', 3], ['A1', 8], ['A2', 1], ['A2', 6], ['A3', 2], ['A3', 7], ['A4', 0], ['A4', 4], ['A4', 5], ['A4', 9]]
[[3, 8], [1], [6], [2], [7], [0], [4, 5, 9]]
-Method2 works------------------
[[3, 8], [1, 6], [2, 7], [0, 4, 5, 9]]
...
1 Answers

The problem with your first method is that you don't save the place that you put for example a code for 'A1', so that you can put in the same place the code of another 'A1' that you would find. I suggest using a dictionary to save places like this:

List3 = []
places = {}
for each_element in List2: 
    if each_element[0] in places:
        List3[places[each_element[0]]].append(each_element[1])
    else:
        List3.append([each_element[1]])
        places[each_element[0]] = len(List3) - 1
print(List3)

And your output is:

[[3, 8], [1, 6], [2, 7], [0, 4, 5, 9]]
Related