How to avoid inconsistent behavior of s [i: -j] when j is sometimes 0?

I create several fragments of the [-WINDOW-i:-i] list, where i is between 32 and 0 :

 vals = [] for i in range(32, -1, -1): vals.append(other_list[-WINDOW-i:-i]) 

When i == 0 , a piece of length 0 is returned:

 other_list[-WINDOW-0:0] 

I do not want to do this to solve this problem:

 vals = [] for i in range(32, -1, -1): if i == 0: vals.append(other_list[-WINDOW:]) else: vals.append(other_list[-WINDOW-i:-i]) 

... because if I have many lists to add to vals , it becomes messy.

Is there a clean way to do this?

+6
source share
1 answer

One way to get around this quirk in the context of Python is to use these facts:

  • false_ish_value or other_value always evaluates other_value
  • 0 - the only integer false-ish in a boolean context
  • s[n:None] equivalent to s[n:]

With this in mind, you can write your fragment as:

 other_list[-WINDOW-i:(-i or None)] 

... and the slice will be interpreted as [-WINDOW-i:None] (which is the same as [-WINDOW-i:] ) only when i (and therefore -i ) 0 .

+7
source

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


All Articles