Implementing python slice notation

前端 未结 6 570
轻奢々
轻奢々 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 06:01

    This is a solution I came up with in C# .NET, maybe not the prettiest, but it works.

    private object[] Slice(object[] list, int start = 0, int stop = 0, int step = 0)
    {
        List result = new List();
    
        if (step == 0) step = 1;
        if (start < 0)
        {
            for (int i = list.Length + start; i < list.Length - (list.Length + start); i++)
            {
                result.Add(list[i]);
            }
        }
        if (start >= 0 && stop == 0) stop = list.Length - (start >= 0 ? start : 0);
        else if (start >= 0 && stop < 0) stop = list.Length + stop;
    
        int loopStart = (start < 0 ? 0 : start);
        int loopEnd = (start > 0 ? start + stop : stop);
    
        if (step > 0)
        {
            for (int i = loopStart; i < loopEnd; i += step)
                result.Add(list[i]);
        }
        else if (step < 0)
        {
            for (int i = loopEnd - 1; i >= loopStart; i += step)
                result.Add(list[i]);
        }
    
        return result.ToArray();
    }
    
        

    提交回复
    热议问题