add elements to indexed list locations

Alexis Roda arv.nntp at gmail.com
Fri Jun 16 13:41:59 EDT 2006


En/na leventyilmaz at gmail.com ha escrit:
> Hi,
> 
> I have a very simple problem, but do not know an elegant way to
> accomplish this.
> ###
> # I have a list of names:
> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
> 
> # and another set of names that I want to insert into
> # the names list at some indexed locations:
> surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
> 
> # The thing I couldn't figure out is, after I insert a
> # surname the rest of the indices are not valid.
> # That is, the following won't work:
> for i, x in surnames.iteritems():
>    names.insert(i,surnames[i])
> ###

In my previous post I've misunderstood the problem. Here is a valid 
solution:

keys = surnames.keys()
keys.sort()
count = 0
for i in keys :
   names.insert(i + count, surnames[i])
   count = count + 1


HTH



More information about the Python-list mailing list