Modifying Element In For List

Duncan Booth duncan.booth at invalid.invalid
Mon Nov 15 12:27:46 EST 2010


octopusgrabbus <old_road_farm at verizon.net> wrote:

> I've written a function which is passed a list that contains rows read
> from a csv file. The function traverses csv_rows, row by row, and
> inspects the first element in each row. The function tests for '', and
> if true, replaces that with a 0.
> 
> I've used the standard Python for syntax for this.
> 
> def cleanMeterID(csv_rows, bad_meter_id_count):
>     d = drIdx()
> 
>     row_number = 0
> 
>     for row in csv_rows:
>         if False == is_number(row[d.MeterID]):
>             csv_rows[row_number][d.MeterID] = 0
>             row_number = row_number + 1
>             bad_meter_id_count[0]= bad_meter_id_count[0] + 1
> 
>     print("Received ", bad_meter_id_count[0], " bad meter ids")
> 
> I believe the logic show above is flawed, because I am not modifying
> elements in the original csv_rows list.

You have a reference to the row, so just modify it directly.

Other points:
bad_meter_id_count should just be a return value: that messing about 
with a list is just plain nasty.
Comparing directly against True or False is error prone: a value in 
Python can be false without actually being equal to False.

def cleanMeterID(csv_rows):
    d = drIdx()
    count = 0

    for row in csv_rows:
        if not is_number(row[d.MeterID]): # or even: if row[d.MeterID]=='':
            row[d.MeterID] = 0
            count += 1

    print("Received {} bad meter ids".format(count))
    return count

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list