Passing Python slice syntax around to functions

前端 未结 3 823
青春惊慌失措
青春惊慌失措 2020-12-16 12:18

In Python, is it possible to encapsulate exactly the common slice syntax and pass it around? I know that I can use slice or __slice__ to emulate sl

3条回答
  •  生来不讨喜
    2020-12-16 13:06

    One way (for simple slices) would be to have the slice argument either be a dict or an int,

    ie

    get_important_values([1, 2, 3, 4], lambda x: (x%2) == 0, {0: -1})
    

    or

    get_important_values([1, 2, 3, 4], lambda x: (x%2) == 0, 1)
    

    then the syntax would stay more or less the same.

    This wouldn't work though, for when you want to do things like

    some_list[0:6:10..]
    

提交回复
热议问题