实现 python 切片表示法

我正在尝试用另一种语言(php)重新实现python切片符号,并寻找一个可以模仿python逻辑的片段(在任何语言或伪代码中)。也就是说,给定一个列表和三元组或其一部分,确定所有参数的正确值或默认值,并将切片作为新列表返回。(start, stop, step)

我试着调查了源代码。该代码远远超出了我的c技能,但我不禁同意评论说:

/* this is harder to get right than you might think */ 

此外,如果已经完成这样的事情,指针将不胜感激。

这是我的测试台(在发布之前确保您的代码通过):

#place your code below
code = """
def mySlice(L, start=None, stop=None, step=None):
or 
<?php function mySlice($L, $start=NULL, $stop=NULL, $step=NULL) ...
or 
function mySlice(L, start, stop, step) ...
"""

import itertools

L = [0,1,2,3,4,5,6,7,8,9]

if code.strip().startswith('<?php'):
     mode = 'php'

if code.strip().startswith('def'):
     mode = 'python'

if code.strip().startswith('function'):
     mode = 'js'

if mode == 'php':
    var, none = '$L', 'NULL'
    print code, '\n'
    print '$L=array(%s);' % ','.join(str(x) for x in L)
    print "function _c($s,$a,$e){if($a!==$e)echo $s,' should be [',implode(',',$e),'] got [',implode(',',$a),']',PHP_EOL;}"

if mode == 'python':
    var, none = 'L', 'None'
    print code, '\n'
    print 'L=%r' % L
    print "def _c(s,a,e):\n\tif a!=e:\n\t\tprint s,'should be',e,'got',a"

if mode == 'js':
    var, none = 'L', 'undefined'
    print code, '\n'
    print 'L=%r' % L
    print "function _c(s,a,e){if(a.join()!==e.join())console.log(s+' should be ['+e.join()+'] got ['+a.join()+']');}"


print

n = len(L) + 3
start = range(-n, n) + [None, 100, -100]
stop  = range(-n, n) + [None, 100, -100]
step  = range(-n, n) + [100, -100]

for q in itertools.product(start, stop, step): 

    if not q[2]: q = q[:-1]

    actual = 'mySlice(%s,%s)' % (var, ','.join(none if x is None else str(x) for x in q))
    slice_ = 'L[%s]' % ':'.join('' if x is None else str(x) for x in q)
    expect = eval(slice_)

    if mode == 'php':
        expect = 'array(%s)' % ','.join(str(x) for x in expect)
        print "_c(%r,%s,%s);" % (slice_, actual, expect)

    if mode == 'python':
        print "_c(%r,%s,%s);" % (slice_, actual, expect)

    if mode == 'js':
        print "_c(%r,%s,%s);" % (slice_, actual, expect)

如何使用它:

  • 保存到文件 (test.py)
  • 将你的 python、php 或 javascript 代码放在 s 之间"""
  • 运行 或 或 或python test.py | pythonpython test.py | phppython test.py | node

答案 1

下面是 C 代码的直接端口:

def adjust_endpoint(length, endpoint, step):
     if endpoint < 0:
         endpoint += length
         if endpoint < 0:
             endpoint = -1 if step < 0 else 0
     elif endpoint >= length:
         endpoint = length - 1 if step < 0 else length
     return endpoint

def adjust_slice(length, start, stop, step):
     if step is None:
         step = 1
     elif step == 0:
         raise ValueError("step cannot be 0")

     if start is None:
         start = length - 1 if step < 0 else 0
     else:
         start = adjust_endpoint(length, start, step)

     if stop is None:
         stop = -1 if step < 0 else length
     else:
         stop = adjust_endpoint(length, stop, step)

     return start, stop, step

def slice_indices(length, start, stop, step):
     start, stop, step = adjust_slice(length, start, stop, step)
     i = start
     while (i > stop) if step < 0 else (i < stop):
         yield i
         i += step

def mySlice(L, start=None, stop=None, step=None):
     return [L[i] for i in slice_indices(len(L), start, stop, step)]

答案 2

这就是我想到的(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

似乎有效 - 让我知道你的想法

希望它有帮助