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

前端 未结 1 393
我在风中等你
我在风中等你 2020-12-17 20:22

I am creating a number of slices [-WINDOW-i:-i] of a list, where i ranges between 32 and 0:

vals = []

fo         


        
1条回答
  •  伪装坚强ぢ
    2020-12-17 20:46

    One workaround for this quirk in Python slicing is to take advantage of these facts:

    1. false_ish_value or other_value always evaluates to other_value
    2. 0 is the only integer that is false-ish in a boolean context
    3. s[n:None] is equivalent to s[n:]

    With those in mind, you can write your slice 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) is 0.

    0 讨论(0)
提交回复
热议问题