Implementing python slice notation

前端 未结 6 557
轻奢々
轻奢々 2021-02-07 05:06

I\'m trying to reimplement python slice notation in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is,

6条回答
  •  失恋的感觉
    2021-02-07 05:42

    This is what I came up with (python)

    def mySlice(L, start=None, stop=None, step=None):
        answer = []
        if not start:
            start = 0
        if start < 0:
            start += len(L)
    
        if not stop:
            stop = len(L)
        if stop < 0:
            stop += len(L)
    
        if not step:
            step = 1
    
        if stop == start or (stop<=start and step>0) or (stop>=start and step<0):
            return []
    
        i = start
        while i != stop:
            try:
                answer.append(L[i])
                i += step
            except:
                break
        return answer
    

    Seems to work - let me know what you think

    Hope it helps

提交回复
热议问题