在[:index]上使用动态索引进行列表切片 [英] List slicing with dynamic index on [:index]
问题描述
我需要使用负动态索引([:-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
注意:我正在使用Python 2.7.
另一个有趣的潜在解决方案.
>>> arr = [1, 2, 3]
>>> index = 0
>>> arr[:-index or None]
[1, 2, 3]
>>> index = 1
>>> arr[:-index or None]
[1, 2]
要在字符串等不可变序列类型上获得更高的性能,可以在切片操作之前检查索引 的值,从而避免在索引为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
在索引为0的情况下,后两个应该快得多,而在其他情况下则可能要慢(或快).
更新的基准代码: http://repl.it/oA5 >
注意:结果在很大程度上取决于Python的实现.
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.
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.
这篇关于在[:index]上使用动态索引进行列表切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!