[Tutor] renumbering a sequence

Dave Angel davea at ieee.org
Sun Apr 5 03:09:36 CEST 2009


Christopher Spears wrote:
> I want to write a script that takes a list of images and renumbers 
> them with a user supplied number. Here is a solution I came up while 
> noodling around in the interpreter:
>>>> >>> alist = ["frame.0001.tif","frame.0002.tif","frame.0003.tif"]
>>>> >>> new_start = 5000
>>>> >>> for x in alist:
>>>>         
> alist = ["frame.0001.tif","frame.0002.tif","frame.0003.tif"]
> >>> new_start = 5000
> >>> for x in alist:
>   
> ...     name, number, ext = x.split(".")
> ...     new_frame = name + "." + str(new_start) + "." + ext
> ...     new_start = new_start + 1
> ...     print new_frame
> ...
> frame.5000.tif
> frame.5001.tif
> frame.5002.tif
>   
> How is that for a solution?  Is there a more elegant way to solve this problem?
>
>   

A few things you could do more elegantly.  Main thing is to avoid 
explictly incrementing new_start.  The trick for that is enumerate.  I'd 
do something like:
     for num, x in enumerate(alist, start=5000) :
        name, dummy, ext = x.split(".")
        new_frame = ".".join( (name, str(num), ext) )
        print new_frame

Notes:   enumerate turns a list of strings into a sequence of num/string 
pairs, where the numbers are sequential starting with 5000.  And 
string.join concatenates all the strings in the list, with "." in 
between them.  It is the inverse of split, so it makes perfect sense.  
Only catch is that you have to use double parentheses, since you have to 
turn those three strings into a list of strings, then pass it to join as 
a single argument.




More information about the Tutor mailing list