I have a list that contains a lot of sublists. i.e.
mylst = [[1, 343, 407, 433, 27],
[1, 344, 413, 744, 302],
[1, 344, 500, 600, 100],
[1, 344, 752, 1114, 363],
[1, 345, 755, 922, 168],
[2, 345, 188, 1093, 906],
[2, 346, 4, 950, 947],
[2, 346, 953, 995, 43],
[3, 346, 967, 1084, 118],
[3, 347, 4, 951, 948],
[3, 347, 1053, 1086, 34],
[3, 349, 1049, 1125, 77],
[3, 349, 1004, 1124, 120],
[3, 350, 185, 986, 802],
[3, 352, 1018, 1055, 38]]
I want to start categorizing this list firstly and making another list by using three steps. First of all, I want to compare sublists when the first item in each sublist is the same, i.e mylist[a][0]==1. Secondly, comparing second item in sublists, and if difference between the second item in the sublist and another second item in the following sulbists under 2, then calculate the difference between third items or fourth items. If either of the difference for third and fourth item is under 10, then I want to append index of the sublist.
The result that I want should be... like this : [0, 1, 3, 4, 6, 7, 10, 11, 12]
Following is my naive attempts to do this.
Following is my naive attempts to do this.
def seg(mylist) :
Segments = []
for a in range(len(mylist)-1) :
for index, value in enumerate (mylist) :
if mylist[a][0] == 1 :
if abs(mylist[a][1] - mylist[a+1][1]) <= 2 :
if (abs(mylist[a][2] - mylist[a+1][2]) <= 10 or
abs(mylist[a][3] - mylist[a+1][3]) <= 10) :
Segments.append(index)
return Segments
or
def seg(mylist) :
Segments= []
for index, value in enumerate(mylist) :
for a in range(len(mylist)-1) :
if mylist[a][0] == 1 :
try :
if abs(mylist[a][1]-mylist[a+1][1]) <= 2 :
if (abs(mylist[a][2]-mylist[a+1][2]) <= 10 or
abs(mylist[a][3] - mylist[a+1][3]) <= 10) :
Segments.append(index)
except IndexError :
if abs(mylist[a][1]-mylist[a+1][1]) <= 2 :
if (abs(mylist[a][2]-mylist[a+1][2]) <= 10 or
abs(mylist[a][3] - mylist[a+1][3]) <= 10):
Segments.append(index)
return Segments
These codes don't look nice at all, and result are not showing as that I intended to. In the bottom one, I wrote try and except to handle index error(list out of range), initially I used 'while' iteration instead of 'for' iteration.
What should I do to get result that I wanted to? How can I correct those codes to look like more 'pythonic' way? Any idea would be great for me, and many thanks in advance.