Passing Python slice syntax around to functions

前端 未结 3 816
青春惊慌失措
青春惊慌失措 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 12:53

    In short, no. That syntax is only valid in the context of the [] operator. I might suggest accepting a tuple as input and then pass that tuple to slice(). Alternatively, maybe you could redesign whatever you're doing so that get_important_values() is somehow implemented as a sliceable object.

    For example, you could do something like:

    class ImportantValueGetter(object):
        def __init__(self, some_list, some_condition):
            self.some_list = some_list
            self.some_condition = some_condition
    
        def __getitem__(self, key):
            # Here key could be an int or a slice; you can do some type checking if necessary
            return filter(self.some_condition, self.some_list)[key]
    

    You can probably do one better by turning this into a Container ABC of some sort but that's the general idea.

    0 讨论(0)
  • 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..]
    
    0 讨论(0)
  • 2020-12-16 13:09

    Perhaps something along the following lines would work for you:

    class SliceMaker(object):
      def __getitem__(self, item):
        return item
    
    make_slice = SliceMaker()
    
    print make_slice[3]
    print make_slice[0:]
    print make_slice[:-1]
    print make_slice[1:10:2,...]
    

    The idea is that you use make_slice[] instead of manually creating instances of slice. By doing this you'll be able to use the familiar square brackets syntax in all its glory.

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