Search code examples
pythonlistalphanumeric

Finding specific elements from an alphanumeric list based on there associated number- python


I have list that contains nested alphanumeric elements. Im looking for a way to find all specific sets in the list that have the same number associated with them. In general the list looks as such [[[a#, b#], [a#, b#]], etc]. The list is as fallows,

A=[[[a2, b4], [a1, b4]],
   [[a1, b1], [a1, b1]],
   [[a3, b2], [a3, b4]],
   [[a2, b2], [a2, b2]]]

I'd like to figure out a way to iterate thru A and find all the sets where the a's and b's in a set are from the same number, like [[ai, bi], [ai, bi]], where the i represent the same number (it can be any number tho, it just has to be the same). The output would look something like this,

B=[[[a1, b1], [a1, b1]],
   [[a2, b2], [a2, b2]]

So far the code Ive worked out looks like this,

B=[]
for i in range(len(A)):
    if A[i][0][0]==A[i][1][0]:
        if A[i][0][1]==A[i][1][1]:
            pair=[[A[i][0][0],Ai][0][1]], [A[i][1][0],A[i][1][1]]]
        B.append(pair)

But this has its own issues as it doesn't take into account that the number between the a's and the b's also need to be the same (in any one set). I'm wondering how to incorporate that into the code or if theres a simply a better overall approach to this.


Solution

  • Use a simple list comprehension. Iterate through A and check if both elements are same.

    In [26]: A=[[['a2', 'b4'], ['a1', 'b4']],
    ...:    [['a1', 'b1'], ['a1', 'b1']],
    ...:    [['a3', 'b2'], ['a3', 'b4']],
    ...:    [['a2', 'b2'], ['a2', 'b2']]]
    
    In [27]: B = [i for i in A if i[0] == i[1]]
    
    In [28]: B
    Out[28]: [[['a1', 'b1'], ['a1', 'b1']], [['a2', 'b2'], ['a2', 'b2']]]