Home > Net >  adding rows based on values of other rows
adding rows based on values of other rows

Time:11-01

I have a list (in a dataframe) that looks like this:

oddnum = [1, 3, 5, 7, 9, 11, 23]

I want to create a new list that looks like this:

newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]
  1. I want to test if the distance between two numbers is 2 (if oddnum[index 1]-oddnum[index] == 2)

  2. If the distance is 2, then I want to add the number following oddnum[index] and create a new list (oddnum[index] 1)

  3. If the distance is greater than two, keep the list as is

I keep getting key error because (I think) the list runs out of [index] and [index 1] no longer exists once it reaches the end of the list. How do I do this?

CodePudding user response:

To pass errors, the best method is to use try and except conditions. Here's my code:

oddnum = [1, 3, 5, 7, 9, 11, 23]
res = [] # The new list
for i in range(len(oddnum)):
    res.append(oddnum[i]) # Append the first value by default
    try: # Tries to run the code
        if oddnum[i]    2 == oddnum[i 1]: res.append(oddnum[i] 1) # Appends if the condition is met
    except: pass # Passes on exception (in our case KeyError)
print(res)

CodePudding user response:

oddnum = [1, 3, 5, 7, 9, 11, 23]

new_list = []

for pos, num in enumerate(oddnum):

    new_list.append(num)
    
    try:

        if num-oddnum[pos 1] in [2, -2]:

            new_list.append(num 1)
    except:

     pass
        
print(new_list)

Use try: except: to prevent exceptions popping up and ignore it

  • Related