-2

let's say i have a list , list=[[0,1,2],[1,2,0],[2,1,3],[3,1,2]]. i want to match and group the arrays position in the list which has same numbers in spite of their position and get their indices. for example my code should give [0,1,2] and [1,2,0] are same and their position is 0 and 1. I need a code to group all the elements in the list like this. I know a basic way of doing this with for and if loop but i want to know is there a efficient way to do this in python.

Edit- I implemented the solution using below code, it is doing what i want to do. I want to know is there a efficient way to do this.

    import numpy as np
    pairs=[[0,1],[1,0],[1,2],[2,1]]
    for j in range(4):
        pairs[j]=sorted(pairs[j])  
    print(pairs)
    pr=(len(pairs))
    unique=np.unique(pairs,axis=0)
    print(unique)
    house_clusters=list()
    for t in range(len(unique)):
        uni=unique[t]
        seq2=list()
        for r in range (pr):
            if np.array_equal(pairs[r],uni):
                seq2.append(r)
        house_clusters.append(seq2)
    print(house_clusters)

result

  • You don't have a list of arrays, you have a tuple of lists. Also what is "pair"? Please edit and format you question accordingly. – Frieder Mar 27 '20 at 12:02
  • I am sorry,i am new to the platform. sometimes i don't know the exact term for somethings. any help is appreciated. thank you – Surya Venkatesh Mar 27 '20 at 13:31

1 Answers1

0

Your question is unclear as mentioned in comments and could potentially be a duplicate. I think what you want is to treat all arrays to be equal on the basis of its constituent elements if that is what you want then try using set and frozenset

''' Example all arrays like [0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0] will be equal to frozenset({0,1,2}) '''
list1 = [[0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0],[2,1,3],[3,1,2]]
tmp ={frozenset(x) for x in list1}
print(tmp)
output: {frozenset({0, 1, 2}), frozenset({1, 2, 3})}

you also mentioned that you already have solution to the question using for and if, try adding it here so that we can figure out what is it that you want exactly.

Rohan Kumar
  • 388
  • 1
  • 3
  • 11
  • Thanks rohan, as you asked i have added my solution, I used unique instead of frozenset but finally what i need is the grouped indices of each frozenset . in your example,finally what i want is [[0,1,2,3,4,5],[6,7]] .you can see the result i have attached. – Surya Venkatesh Mar 30 '20 at 11:03