Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - List slicing with dynamic index on [:index]

I need to slice a list using negative dynamic indexes ([:-index]). This was easy until I realized that if the value of my dynamic index was 0, no items were returned, instead of returning the entire list. How can I implement this in a way that when the index is 0, it returns the entire string? My code is very long and complicated, but basically this example shows the problem:

    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

Note: I am using Python 2.7.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another potential solution for fun.

>>> arr = [1, 2, 3]
>>> index = 0
>>> arr[:-index or None]
[1, 2, 3]
>>> index = 1
>>> arr[:-index or None]
[1, 2]

For higher performance on immutable sequence types like strings, you can avoid slicing the sequence entirely in the case that index is 0 by checking the value of index before the slice operation.

Here's three functions to test in terms of performance:

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

The latter two should be much faster in the case where index is 0, but may be slower (or faster) in other cases.


Updated benchmark code: http://repl.it/oA5

Note: The results depend quite a bit on the Python implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...