add elements to indexed list locations

Steven Bethard steven.bethard at gmail.com
Sat Jun 17 23:28:37 EDT 2006


levent wrote:
> Thanks for the answers. Enumerating in reverse is indeed quite a smart
> idea.
> 
> The fact is though, I overly simplified the task in the super-hero
> example. In the real case, the dictionary keys are not necessarily the
> indices for inserts; that is to say, the inserts do not necessarily
> take place in some sorted order.
> 
> I think I was thinking more of a linked-list idea, where you do not
> store the indices as integers to some random access array but rather as
> pointers into list's nodes. Then the subsequent inserts would not hurt
> previously stored pointers. For those who know a bit C++/STL here is a
> sketch of the idea:

Sorry, I don't know C++/STL, so I don't understand the example you gave. 
  If your dict doesn't already come with the indices, can't you just 
create a dict that does?

 >>> heros = ["super", "clark", "spider", "peter", "bat", "bruce"]
 >>> names = dict(clark="kent", peter="parker", bruce="wayne")
 >>> heros_indices = {}
 >>> for index, hero_word in enumerate(heros):
...     if hero_word in names:
...         heros_indices[index + 1] = names[hero_word]
...
 >>> for index in sorted(heros_indices, reverse=True):
...     heros.insert(index, heros_indices[index])
...
 >>> heros
['super', 'clark', 'kent', 'spider', 'peter', 'parker', 'bat', 'bruce', 
'wayne']

STeVe



More information about the Python-list mailing list