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

标签 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

注意:我使用的是 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/

相关文章:

go - 如何填充包含大小未知的结构 slice 的结构

python - 在 PyGObject 自省(introspection)中,GTK w/Python 中的线程是否发生了变化?

python - 使用两个变量进行迭代

python - 使用 pygame 进行 LaTeX 类型渲染

python - 如何使用/从命名空间中获取列表元素?

arrays - 在 Kotlin 中获取索引从末尾开始计数的元素

javascript - Flask 不返回 bool 复选框值

list - 如何创建包含容器具有属性的列表的 POJO?

python,随机播放直到列表完全不同

string - 在 Haskell 中,如何在两个索引之间获取 Text 的子字符串?