Extract numbers from a list

I created a list (which is sorted):

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

I want to extract numbers from this list that are in at least five places from each other and enter them in another list. It scares. This is an example of how I want the output:

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

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

I 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 result:

 outlist = [0, 12, 19] 

Of course, the numbers are at least 5, but I miss some of the necessary values.

Any ideas on how I can accomplish this task?

+5
source share
4 answers

You need to track the last item you added to the list, and not just compare with 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] 
+4
source

That should do the trick. Here, as I said in a comment, the outlist initialized with the first value of the indexlist , and the iterated elements of the indexlist compared with it. This is a tough decision. But it 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] 
+1
source

Tim Pitzker’s answer is correct, but this can also be done without storing the last added item in a separate variable. Instead, you can read the last value in the list:

 >>> indexlist = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33] >>> outlist = [] >>> for n in indexlist: ... if not outlist or n > outlist[-1] + 5: ... outlist.append(n) ... >>> outlist [0, 7, 19, 25, 31] 
+1
source

I assume your index_list sorted. Then it will give you only MIN_INDEX_OFFSET indexes.

 MIN_INDEX_OFFSET = 5; index_list = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33]; last_accepted = index_list[0]; out_list = [last_accepted]; for index in index_list: if index-last_accepted > MIN_INDEX_OFFSET: out_list.append(index); last_accepted = index; print(out_list) 
0
source

Source: https://habr.com/ru/post/1247632/


All Articles