Krish
Krish

Reputation: 1081

(python) Why doesn't .append() work here?

I have some code that effectively replaces this excel spreadsheet where I am trying to find the difference between two times. Depending on the state of the second column of that value I want to segregate this into two columns.

excel spreadsheet

I converted the data in the first two columns into a list of lists in the form

[...[2.96738, 0], [3.91727, 1], [3.9729, 0], [4.88419, 1], [4.93686, 0], [5.86113, 1], [5.91125, 0]...]

Running my code:

    def Delta_Time_One_State(CleanState):
        for counter, value in enumerate(CleanState[1:]):
            DeltaT = value[0] - CleanState[counter][0]
            Lgt_cut_Time = []
            Lgt_Uncut_Time = []
            if value[1] == 0:
                Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
            else:
                Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])


    clean_state_A = [[0.0, 0], [0.03253, 1], [0.08479, 0], [0.98748, 1], [1.03717, 0], ... [483.8888, 0], [484.6563, 1]]
    Delta_Time_One_State(clean_state_A)

gives me

Lgt_Uncut_Time = [[485.04004999999995, 0.7674999999999841]]
Lgt_cut_Time = []

Which can't be right because the for loop runs through almost all of clean_state_A. Since every loop passes through the if statement something appears to be wrong with the .append function but I can't tell what.

Upvotes: 1

Views: 55

Answers (2)

Benjamin Hoving
Benjamin Hoving

Reputation: 84

You are recreating the Lgt_cut_Time and Lgt_Uncut_Time lists every loop.

def Delta_Time_One_State(CleanState):
    for counter, value in enumerate(CleanState[1:]):
        DeltaT = value[0] - CleanState[counter][0]
        Lgt_cut_Time = []
        Lgt_Uncut_Time = []
        if value[1] == 0:
            Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
        else:
            Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])

Just move them outside of the loop so that they accumulate the results instead of replacing them on every loop.

def Delta_Time_One_State(CleanState):
    Lgt_cut_Time = []
    Lgt_Uncut_Time = []
    for counter, value in enumerate(CleanState[1:]):
        DeltaT = value[0] - CleanState[counter][0]
        if value[1] == 0:
            Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
        else:
            Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])

Upvotes: 1

Jtcruthers
Jtcruthers

Reputation: 956

Every loop you are redefining the two lists. Move them outside of the for loop so you're appending to the same list every iteration.

def Delta_Time_One_State(CleanState):
    Lgt_cut_Time = []
    Lgt_Uncut_Time = []
    for counter, value in enumerate(CleanState[1:]):
        DeltaT = value[0] - CleanState[counter][0]
        calculated_data = [value[0] + DeltaT / 2, DeltaT]
        if value[1] == 0:
            Lgt_cut_Time.append(calculated_data)
        else:
            Lgt_Uncut_Time.append(calculated_data)

Upvotes: 3

Related Questions