Replace 0 values by previous positive value in list

Hi everyone,

I can’t figure how to solve an “apparently’“ simple problem on lists.

I’m dealing with a list of values following this pattern :

{0}
[400;0;0;0;0;120;0;0;30;0]
{1}
[650;0;0;320;0;0;0;0;0;0;0;110;0]

I’d like to replace the 0 values by the previous positive value. Following this simple rule, I expect :

{0}
[400;400;400;400;400;120;120;120;30;30]
{1}
[650;650;650;320;320;320;320;320;
320;320;320;110;110]

As you could have seen, number of items in branches may differ.

I really hope someone could help me :slight_smile:

Thanks,
Thib

Is it always that structure? Single digits separated by zeros? Never two non-zero numbers next to each other?

Does it matter if it were?

Not sure till I try, but it’s good to have clear specification of a problem :slight_smile:

It’s just a falling edge detector.

but we are sure that the first item is not 0 ?

I would assume, but in that case make <“null”>

replace0withprev_jvs01.gh (13.7 KB)

3 Likes

you still have to define:
what should happen if the list starts with 0 ?

[0;0;400;0;0;0;0;120;0;0;30;0]

and yes, solve it by a simple script as @Jakob_v_Schirmeister showed.

Like I said, you then start replacement with a null.

Well, just for fun, here’s a way without a script :slight_smile:

replace following zeros TN.gh (9.0 KB)

2 Likes


Replace 0 values by previous positive value in list VR 02.gh (16.9 KB)

1 Like

:smiling_face_with_tear:

impressive!
(how complex/complicated vanilla can be)
but a good lesson!

Hi @Tom_Newsom & @Volker_Rakow

You’re correct, I didn’t explain a lot about the lists structure.

  • It always begins with a non-zero
  • 2 non-zero numbers can be consecutive
  • all numbers are integer by the way

Your script Tom seems to work, but I’m facing a problem when 2 non-zero numbers are consecutive.

Volker, you may have solve my problem. I’ll test it !

Thank you both for quick answers

It should. I’ve stress-tested it. The only thing that may trip it up is negative numbers? I don’t know if you will have any of those. So for instance:

[-12, 30, -4, 0, 0, 0]

would translate to:
[-12, 30, -4, -4, -4, -4]

instead of:
[-12, 30, 30, 30, 30, 30]

and you have asked that the zeros be replaced “by the previous positive value in [the] list”

Pretty sure this revision of my version covers all these reqs: consecutive non-zeros, cull leading zeros, negative==zero. If there’s some other behaviour for negatives, it’d be a simple fix.

replace following zeros TN2.gh (11.1 KB)

1 Like

Either negative==zero, or negative==a non-zero to be skipped over until the first previous positive integer is found. That’s still not clear.

This is trivial in code…

Replace 0 values by previous positive value in list JS Python.gh (7.5 KB)

Note that you need to set the x input to List Access mode.

HTH
Jeremy

2 Likes

As probably most things are :sweat_smile: