Find the index value of similar items in array

Question:

I created a for loop that will pinpoint the location when name and DB are the same value. The problem is if there is a value that is not present in name, the index becomes -2, and will be -2 for the rest of the array even when the values are present in both arrays.

How can I fix this? Also, is there a way to print out the values from the name array that are indexed -2 and to check for duplicates in DB?

For example:

DB = ['a','b','g','f','g']
name = ['a','e','b','p']

code output: [0, -2, -2, -2]

wanted output: [0, -2, 1, -2]
The following is a list of name not present in the DB array: e,p
The calculation has been aborted, there is a duplicate DB: g

Code:

DB = ['a','b','g','f','g']
name = ['a','e','b','p']

wanted_columns=[-2 for a in range(len(name))]

try:
    for i in range(0,len(name)):
        wanted_columns[i] = DB.index(name[i])
        
except ValueError:
    print('The following is a list of tags not present in the DB array: {}' .format(name[i]))
Asked By: HoneyWeGOTissues

||

Answers:

You need to put try/except inside the loop. Your code ends the loop when the exception happens.

When if you do it this way, you don’t need to pre-fill the list, you can use append().

DB = ['a','b','g','f','g']
name = ['a','e','b','p']
indexes = []
wanted_columns = []

for val in name:
    try:
        indexes.append(DB.index(val))
    except:
        indexes.append(-2)
        wanted_columns.append(val)

print(f'Indexes: {indexes}')
print(f'The following is a list of tags not present in the DB array: {",".join(wanted_columns)}')
Answered By: Barmar

The problem is that once you hit an error in your for loop, the except statement is executed, and the script terminates (the other iterations won’t be run). Move the try-except statement inside the for loop.

DB = ['a','b','g','f','g']
name = ['a','e','b','p']

wanted_columns=[-2 for a in range(len(name))]


for i in range(0,len(name)):
    try:
        wanted_columns[i] = DB.index(name[i]) 
    except ValueError:
        print('The following is a list of tags not present in the DB array:' .format(wanted_columns[i]))
Answered By: userE
  1. The answer to the first question is putting for loop outside the try...except statement.
unique_name = []
for i in range(0,len(name)):
    try:
        wanted_columns[i] = DB.index(name[i])
    except ValueError:
        unique_name.append(name[i])
print('The following is a list of tags not present in the DB array: {}' .format(','.join(unique_name)))

BTW, I provide another solution to do this.

wanted_columns = [ DB.index(v) if DB.count(v) else -2 for v in name ]
unique_name = [ v for v in name if v not in DB ]
  1. As for checking for duplicates in DB, you can also use count().
duplicates = { v for v in DB if DB.count(v) > 1 }
print('The calculation has been aborted, there is a duplicate DB: {}'.format(','.join(duplicates)))
Answered By: ILS