I have a string that I need to find index in a list ignoring cases.
MG
['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
I want to find the index of MG in the following line as a list.
One of the more elegant ways you can 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 makes a generator that yields the index of the next case insensitive occurrence of mg
in the list, then invokes next()
once, to retrieve the first index. If you had several occurrences of mg
in the list, calling next()
repeatedly would yield them all.
This also has the benefit of being marginally less expensive, since an entire lower cased list need not be created; only as much of the list is processed as needs to be to find the next match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With