在[:index]上使用动态索引列出切片

And*_* La 7 python list slice

我需要使用负动态索引([: - index])对列表进行切片.这很容易,直到我意识到如果我的动态索引的值为0,则没有返回任何项目,而是返回整个列表.我怎样才能以索引为0的方式实现它,它返回整个字符串?我的代码很长很复杂,但基本上这个例子显示了问题:

    arr='test text'
    index=2
    print arr[:-index]
    >>'test te'    #Entire string minus 2 from the right
    index=1
    print arr[:-index]
    >>'test tex'    #Entire string minus 1 from the right
    index=0
    print arr[:-index]
    >>''           #I would like entire string minus 0 from the right
Run Code Online (Sandbox Code Playgroud)

注意:我使用的是Python 2.7.

Sha*_*ank 9

另一个有趣的潜在解决方案

>>> arr = [1, 2, 3]
>>> index = 0
>>> arr[:-index or None]
[1, 2, 3]
>>> index = 1
>>> arr[:-index or None]
[1, 2]
Run Code Online (Sandbox Code Playgroud)

对于像字符串这样的不可变序列类型的更高性能,通过在切片操作之前检查索引的值,可以避免在索引为0的情况下完全切片序列.

这里有三个在性能方面进行测试的功能:

def shashank1(seq, index):
    return seq[:-index or None]

def shashank2(seq, index):
    return index and seq[:-index] or seq

def shashank3(seq, index):
    return seq[:-index] if index else seq
Run Code Online (Sandbox Code Playgroud)

后两者应当是在指数是0的情况下更快,但也可以是在其它情况下更慢(或更快).


更新了基准代码: http ://repl.it/oA5

注意:结果在很大程度上取决于Python的实现.


Cor*_*mer 6

它有点偏离切片表示法的清晰度,但你可以这样做

>>> arr[: len(arr) - 2]
'test te'
>>> arr[: len(arr) - 1]
'test tex'
>>> arr[: len(arr) - 0]
'test text'
Run Code Online (Sandbox Code Playgroud)


jon*_*rpe 5

您可以使用None而不是0获取完整切片:

>>> arr = [1, 2, 3]
>>> index = 1
>>> arr[:-index if index else None]
[1, 2]
>>> index = 0
>>> arr[:-index if index else None]
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

我的测试:

import timeit

def jonrsharpe(seq, index):
    return seq[:-index if index else None]

def Cyber(seq, index):
    return seq[:len(arr) - index]

def shashank(seq, index):
    return seq[:-index or None]

if __name__ == '__main__':
    funcs = ('jonrsharpe', 'Cyber', 'shashank')
    arr = range(1000)
    setup = 'from __main__ import arr, {}'.format(', '.join(funcs))
    for func in funcs:
        print func
        for x in (0, 10, 100, 1000):
            print x,
            print timeit.timeit('{}(arr, {})'.format(func, x), setup=setup)
Run Code Online (Sandbox Code Playgroud)

和结果:

jonrsharpe
0 2.9769377505
10 3.10071766781
100 2.83629358793
1000 0.252808797871
Cyber
0 3.11828875501
10 3.10177615276
100 2.82515282642
1000 0.283648679403
shashank
0 2.99515364824
10 3.11204965989
100 2.85491723351
1000 0.201558213116
Run Code Online (Sandbox Code Playgroud)