Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting numbers from list

Tags:

python

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?

like image 454
interstellar Avatar asked Apr 21 '16 14:04

interstellar


People also ask

How do you take a number out of a list in Python?

The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do I extract a number from a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).


2 Answers

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]
like image 61
Tim Pietzcker Avatar answered Sep 29 '22 20:09

Tim Pietzcker


This should do the trick. Here, as I said in comment, the outlist is initialised with the first value of indexlistand iterated indexlist elements are compared to it. It is a rough solution. But works.

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

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

output:

>>outlist

[0, 7, 19, 25, 31]
like image 30
kada Avatar answered Sep 29 '22 19:09

kada