user15141497
user15141497

Reputation: 73

adding rows based on values of other rows

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?

Upvotes: 0

Views: 43

Answers (2)

KillerRebooted
KillerRebooted

Reputation: 659

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

Upvotes: 1

The Myth
The Myth

Reputation: 1218

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)

Upvotes: 1

Related Questions