is there a better way...

Eddie Corns eddie at holyrood.ed.ac.uk
Fri May 10 15:03:29 EDT 2002


Christopher Encapera <ChrisE at lantech.com> writes:

>to loop over a list and replace an element based on its value than:

>x = [1,2,3,4,5,6,7,8,9]
>y = len(x)
>z = 0
>while z < y:
>    element = x[z]
>    if element == 5: x[z] = '678'
>    z = z +1
> 

>Another words is there a way to do this with a "for" statement - some method
>that will return the current z (of x[z]) in the loop?
>(My goal is to open Windows logon scripts and update the path to the latest
>virus DAT's)

I have the following routine defined in my utils library

from __future__ import generators
# add sequence numbers to a sequence.
# Instead of doing eg:
#   for a,b in seq:
# do:
#   for n,(a,b) in number_seq (seq):
def number_seq (seq):
    cnt = 0
    for item in seq:
        yield (cnt, item)
        cnt += 1

Using this you would do:
x = [1,2,3,4,5,6,7,8,9]
for n,element in number_seq (x):
    if element == 5: x[n] = '678'

Or to replace several things in one pass:
froms=[5,8]
tos  =[678,99]

for n,element in number_seq (x):
    if element in froms:
        x[n] = tos[froms.index(element)]

A dictionary would be more elegant in this example I guess.

Needs 2.2 obviously and a better name probably.

Eddie



More information about the Python-list mailing list