interstellar interstellar - 7 months ago 14
Python Question

extracting numbers from list

I've created a list (which is sorted):

indexlist = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33]


I want to extract the numbers from this list that are at least five away from each other and input them into another list. This is kind of confusing. This is an example of how I want the output:

outlist = [0, 7, 19, 25, 31]


As you can see, none of the numbers are within 5 of each other.

I've tried this method:

for index2 in range(0, len(indexlist) - 1):
if indexlist[index2 + 1] > indexlist[index2] + 5:
outlist.append(indexlist[index2])


However, this gives me this output:

outlist = [0, 12, 19]


Sure, the numbers are at least 5 away, however, I'm missing some needed values.

Any ideas about how I can accomplish this task?

Answer

You need to keep track of the last item you added to the list, not just compare to the following value:

In [1]: indexlist = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33]
In [2]: last = -1000 # starting value hopefully low enough :)
In [3]: resultlist = []
In [4]: for item in indexlist:
   ...:     if item > last+5:
   ...:         resultlist.append(item)
   ...:         last = item
   ...:
In [5]: resultlist
Out[5]: [0, 7, 19, 25, 31]
Comments