[Tutor] single key ordered sequence

spir denis.spir at free.fr
Thu Jan 15 12:48:00 CET 2009


a little algorithmic question.

I have a list of tuples element, in which the first item is a kind of key. I need a target list
with only one tuple per key. But the order must be kept -- so that I cannot use a temp dictionary.
Additionally, in this case the chosen element for a repeted key is the last one occurring in
source list.

How would you do that? 
I used the following method that walks through the list with indexes in top-down order, and
"marks" items to delete by "None-ing" them. But this a ugly trick imo, and I find the overall
method to complicated for such a simple task. There shold be a clear one-liner for that, I guess.

Also, how to practically walk in reverse order in a list without copying it (e.g. items[::-1]),
especially if i need both indexes and items (couldn't find with enumerate()).

items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for index in range(len(items)-1,-1,-1):
	key = items[index][0]
	if key in keys:
		items[index] = None
items = [item for item in items if item is not None]

la vida e estranya

More information about the Tutor mailing list