tags:

views:

50

answers:

2
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?

+2  A: 

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
Walter Mundt
sorry, updated my question it was not so clear before
I__
Okay, I've updated my answer to answer your question better now.
Walter Mundt
+2  A: 

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] = ''
sth
thank you very much!! what does range do??
I__
@I__: `range` is a standard library function that returns a list of numbers, from 0 to the one given as parameter (exclusive). Like `range(5)` == `[0,1,2,3,4]`. See http://docs.python.org/library/functions.html#range
sth
If `len(row)` is large I'd use `xrange` instead of `range`; it works the same in a for loop but avoids actually building the list in memory.
Walter Mundt