Kimono 1
Kimono 1

Reputation: 33

Is there an efficient way to search a list with another list maintaining the list's order?

I am just starting to learn python. I need to search one list with another but I have to maintain the order of the list i'm searching with. EX:

MylistA = [A, B, G, S, X]

MylistB = [A, G, B]

I want this to return false as ListB isn't in the same order as ListA. However, if it was:

ListA =[A, B, G, S, X]
ListB =[A, B, G]

I would want this to return True.

The following is what I have tried however it takes up many lines and is inefficient.

MylistA = [A, Q, V, B, G, D, F, R, T, B, G, S, Q]
MylistB = [B, G, D, F, R, T]

ListFound = 0
Pos1 = 0
Pos2 = 1
Pos3 = 2
Pos4 = 3
Pos5 = 4
Pos6 = 5

Pos1A = 0
Pos2A = 1
Pos3A = 2
Pos4A = 3
Pos5A = 4
Pos6A = 5

while Pos6 <= len(MylistA):
    if MylistA[pos1] == MylistB[Pos1A] and \
            MylistA[pos2] == MylistB[Pos2A] and \
            MylistA[pos3] == MylistB[Pos3A] and \
            MylistA[pos4] == MylistB[Pos4A] and \
            MylistA[pos5] == MylistB[Pos5A] and \
            MylistA[pos6] == MylistB[Pos6A]:
        print("MylistB found within MylistA at positions", Pos1, Pos2, Pos3, Pos4,     
               Pos5, Pos6)
        MylistFound += 1
    elif Pos6 >= len(ListA):
        print("MylistB was found", ListFound, "times within MylistA") 
    Pos1 += 1
    Pos2 += 1
    Pos3 += 1
    Pos4 += 1
    Pos5 += 1
    Pos6 += 1

This works as expected however takes up many lines and I'm looking for an efficient method to achieve the same results. Thanks for the help.

Upvotes: 3

Views: 70

Answers (5)

Pedro Lobito
Pedro Lobito

Reputation: 98881

You can create something like:

ListA = ["A", "Q", "V", "B", "G", "D", "F", "R", "T", "B", "G", "S", "Q"]
ListB = ["B", "G", "D", "F", "R", "T"]

for x in range(0, len(ListA)):
    if ListA[x:len(ListB)+x] == ListB:
        print("Full Match", ListA[x:len(ListB)+x])
        print("Positions", "{}:{}".format(x, len(ListB)+x))
        break

# Full Match ['B', 'G', 'D', 'F', 'R', 'T']
# Positions 3:9 # last value (9) is exclusive

Demo

Upvotes: 2

Cryckx
Cryckx

Reputation: 719

Converting the list to string before the comparison will allow you to do it in 3 lines :.

Code

   ListA = [10,2,3,4,5,6,7]
   ListB = [10,2]

   str1 = ' '.join(str(e) for e in ListA)
   str2 = ' '.join(str(e) for e in ListB)

   print(str2 in str1)

output

>>>true

Upvotes: -1

Joanne
Joanne

Reputation: 1

You could try to check the index of each element of ListB in ListA and after that check if they are in the right order:

ListA = ["A","Q","V","B","G","D","F","R","T","B","G","S","Q"]
ListB = ["B","G","D","F","R","T"]

indices=[]
for k in ListB:
  indices.append(ListA.index(k))

if sorted(indices) == indices:
   print "ListB is in ListA in the correct order"
else:
   print "ListB is not in ListA in the correct order"

Upvotes: 0

redhatvicky
redhatvicky

Reputation: 1930

import collections 

inputList1 = [1, 2, 4, 3, 5] 
inputList2 = [1, 2, 4, 3, 5] 
print ("The first list is : " + str(inputList1)) 
print ("The second list is : " + str(inputList2)) 

# Using Sorting
inputList1.sort() 
inputList2.sort() 
if inputList1 == inputList2: 
    print ("The lists are identical") 
else : 
    print ("The lists are not identical")

# using Collection Counter  
if collections.Counter(inputList1) == collections.Counter(inputList2): 
    print ("The lists are identical") 
else : 
    print ("The lists are not identical")

Upvotes: 0

Ma0
Ma0

Reputation: 15204

Here is how I would do it:

def compare(lst_a, lst_b):
    try:
        temp = [lst_a.index(x) for x in lst_b]
    except ValueError:
        res = False
    else:
        res = temp == sorted(temp)
    return res

Some test runs:

ListA = ['A', 'B', 'G', 'S', 'X'] 
ListB = ['A', 'G', 'B']
ListC = ['A', 'B', 'G']
ListD = ['A', 'B', 'FOO']

print(compare(ListA, ListB))  #-> False
print(compare(ListA, ListC))  #-> True
print(compare(ListA, ListD))  #-> False ('FOO' does not exist at all in ListA)

This works by getting the index of all entries in ListB from ListA and storing them on a new list temp. If temp is sorted (temp == sorted(temp)), then your rule has been respected, otherwise not.

Upvotes: 0

Related Questions