Find the index of a row that ignores cases

I have a line where I need to find the index in a list ignoring cases.

MG
['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']

I want to find the MG index in the next line as a list.

+5
source share
3 answers

you can ignore cases by converting the generic list and the element you want to find in lowercase.

>>> to_find = 'MG'
>>> old_list =  ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> new_list = [item.lower() for item in old_list]
>>> new_list.index(to_find.lower())
3
+4
source

One of the most elegant ways to do this is to use a generator:

>>> list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> next(i for i,v in enumerate(list) if v.lower() == 'mg')
3

The above code creates a generator that gives the index of the next case-insensitive appearance mgin the list, and then calls next()once to get the first index. If there were several entries in the list mg, a multiple call next()would give them everything.

, ; , .

+11
my_list = ['one', 'TWO', 'THree']

try:
    my_list.lower().index('tWo'.lower())
except ValueError:
    return -1

Returns 1


try:
    my_list.lower().index('fouR'.lower())
except ValueError:
    return -1

Returns -1

-1
source

All Articles