Basically, I have a list that contains all the possibles values of the second list. For example:
First list (Possible values):
list1 = ['cat','dog','pig']
Second list:
list2 = ['dog','cat','cat','cat','dog','pig','cat','pig']
I want to compare those lists and substitute all the strings in the second list to the index of the first one.
So expect something like this:
list2 = [1,0,0,0,1,2,0,2]
I've tried it in several different ways. The first one, although it worked, was not an intelligent method. Since if the first list had a huge variety of possible values, this strategy would not be functional to code.
That was the first solution:
list3 = []
for i in list2:
if i == 'cat':
i = 0
list3.append(i)
elif i == 'dog':
i = 1
list3.append(i)
elif i == 'pig':
i = 2
list3.append(i)
list2 = list3
print(list2)
output
[1, 0, 0, 0, 1, 2, 0, 2]
But I want a solution that works in a huge variety of possible values without having to code each test.
So I tried this (and other failed attempts), but it isn't working
for i in list2:
for j in list1:
if i == j:
i = list1.index(j)