我需要使用负动态索引 ([:-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 实现。
关于python - 在 [ :index] 上使用动态索引列出切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221432/