Question

drug_input=['MORPHINE','CODEINE']    
def some_function(drug_input)      
      generic_drugs_mapping={'MORPHINE':0,
                                'something':1,
                                'OXYCODONE':2,
                                'OXYMORPHONE':3,
                                'METHADONE':4,
                                'BUPRENORPHINE':5,
                                'HYDROMORPHONE':6,
                                'CODEINE':7,
                                'HYDROCODONE':8}

row is a list.

I would like to set all the members of row[..]='' EXCEPT for those that drug_input defines, in this case it is 0, and 7.

So row[1,2,3,4,5,6,8]=''

If row is initially:

row[0]='blah'
row[1]='bla1'
...
...
row[8]='bla8'

I need:

row[0]='blah' (same as before)
row[1]=''
row[2]=''
row[3]=''
...
...
row[7]='bla7'
row[8]=''

How do I do this?

Was it helpful?

Solution

You could first create a set of all the indexes that should be kept, and then set all the other ones to '':

keep = set(generic_drugs_mapping[drug] for drug in drug_input)
for i in range(len(row)):
  if i not in keep:
    row[i] = ''

OTHER TIPS

I'd set up a defaultdict unless you really need it to be a list:

from collections import defaultdict # put this at the top of the file

class EmptyStringDict(defaultdict):
    __missing__ = lambda self, key: ''

newrow = EmptyStringDict()
for drug in drug_input:
    keep = generic_drugs_mapping[drug]       
    newrow[keep] = row[keep]
saved_len = len(row) # use this later if you need the old row length
row = newrow

Having a list that's mostly empty strings is wasteful. This will build an object that returns '' for every value except the ones actually inserted. However, you'd need to change any iterating code to use xrange(saved_len). Ideally, though, you would just modify the code that uses the list so as not to need such a thing.

If you really want to build the list:

newrow = [''] * len(row) # build a list of empty strings
for drug in drug_input:
    keep = generic_drugs_mapping[drug]       
    newrow[keep] = row[keep] # fill it in where we need to
row = newrow # throw the rest away
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top