common problem - elegant solution sought

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Jan 15 06:19:48 EST 2008


Helmut Jarausch a écrit :
> Hi,
> 
> I'm looking for an elegant solution of the following tiny but common 
> problem.
> 
> I have a list of tuples  (Unique_ID,Date) both of which are strings.
> I want to delete the tuple (element) with a given Unique_ID, but
> I don't known the corresponding Date.

If you don't care about ordering, you could use a dict:

L=[("a","070501"),("b","080115"),("c","071231")]
d = dict(L)
del d['b']
L = d.items()

But I guess you care about ordering !-)

Anyway, you can still use a dict to find out the date part:

L=[("a","070501"),("b","080115"),("c","071231")]
d = dict(L)
t = ('b', d['b'])
L.remove(t)

Or you could build an 'index' list to find out the appropriate index:
L=[("a","070501"),("b","080115"),("c","071231")]
index = [key for key, val in L]
pos = index.index('b')
del L[pos]

> My straight forward solution is a bit lengthy, e.g.
> 
> L=[("a","070501"),("b","080115"),("c","071231")]
> pos=-1
> found=-1
> for (Key,Date) in L :
>     pos+= 1
>     if  Key == "b" :
>         found= pos
>         break
> 
> if  found >= 0 :
>     del L[found]
> 
> print L

You could have used the enumerate(seq) function here. And since you're 
breaking out once the element deleted, you could as well delete it from 
within the loop:

for pos, (key, date) in enumerate(L):
   if key == 'b':
     del L[pos]
     break


Benchmarking left as an exercice to the reader !-)

Also note that the "best" solution may depend on your real use case and 
dataset.



More information about the Python-list mailing list