common problem - elegant solution sought

Diez B. Roggisch deets at nospam.web.de
Tue Jan 15 12:03:25 CET 2008


Helmut Jarausch wrote:

> 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.
> 
> 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
> 
> Most probably there are much more elegant solutions.
> Unfortunately, the index-list-method doesn't take an
> additional function argument for the comparisons.
> 
> Many thanks for your hints,

Several solutions:

 - use a different datastructure, as others suggested

 - use a database. SQLite for example.

 - replace the list in-place like this:

L[:] = [(k, d) for k, d in L if k != "b"]

Diez



More information about the Python-list mailing list