Domanda

I am trying to write over an existing list and skip over any index in the list where value[i] = -1, preserving that value at the correct index.

One problem is the last_item value seems to wrap around to the end of the list, is there a way to prevent that? Otherwise, is there a better way to do this? This seems too clumsy with all the logic.

The data looks like:

-1
 1
 2
 3
-1
 1
 2
 3

And Im trying to get it to look like this:

-1
 1
 2
 3
-1
 4
 5...

EDIT I modified the code that Alex posted below, it is working great now. Here is the code I used:

count = 1
for i range(len(my_list)):
    if my_list[i] == -1:
        new_list.append(-1)
    else:
        my_list[i] = count
        count += 1
        new_list.append(my_list[i])
È stato utile?

Soluzione

You probably want to brush up on python lists, python loops, and iteration/indexing in general before you start to write this code. Here are some pages you might find useful

An Intro to Python Lists

For Loops in Python

Looping with Lists in Python

Another note, just because you set a variable equal to an element in a list, you can't expect that element in that list to change if you change the variable. That's like saying, I'm going to make a copy of this cookie that looks and tastes just like this other cookie. Then, if you eat the second cookie (the one you made), the first one will still exist until you go in and actually eat that cookie.

The same goes for that iterating variable, i. When you check if i==-1, you're really only saying "Is this the first loop in my loop?" because you're looping starting at -1. This should all make more sense when you glance over those loop articles.

Awesome, the input/output data helps a lot. It makes more sense now.

How about this:

count = 1
for i range(len(my_list)):
    if my_list[i] = -1:
        continue
    else:
        my_list[i] = count
        count++

Where my_list is the input list

I'm not 100% understanding the problem here, but I think I do. And this code should give you the output you want given the input you provided. HTH

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top