lundi 26 avril 2021

merge list of lists if variable is of certain value

I have a list containing lists:

[[0, 146, 0], [146, 170, 1], [170, 220, 3], [220, 231, 1], [231, 247, 0], [247, 258, 1], [258, 334, 3], [334, 352, 1], [352, 367, 0], [367, 385, 1], [385, 2917, 3]

I want to merge consecutive lists, if their value in the third position is either 1 or 3 and leave lists having a value of 0 in the third position as they are, keeping only the first value of the first list and the 2nd of the added list.

So the output after merging would look like that:

[[0, 146, 0], [146, 231, 1], [231, 247, 0], [247, 352, 1], [352, 367, 0], ...

First step I did was to make all 3's 1's:

for values in list:
    if values[2] == 3:
        values[2] = 1

to get:

[[0, 146, 0], [146, 170, 1], [170, 220, 1], [220, 231, 1], [231, 247, 0], [247, 258, 1], [258, 334, 1], [334, 352, 1], [352, 367, 0],...

As the final step I'm thinking about an if-condition, like:

x = 0        
if list[x][2] == list[x+1][2]:
  list[x]+list[x+1]
  x+=1

Is there a smooth way to do this? thx in advance for your input!

Aucun commentaire:

Enregistrer un commentaire