如何在切片为索引值时切片

时间:2017-11-20 19:37:10

标签: python string

最狡猾的方式是什么:

Data

如果myIndi​​ces为"hello"[myIndices] ,那么它就会让我回复#34; el"。

我很高兴使用numpy或其他套餐。我可以在R中做类似的事情,但似乎无法在python中工作。谢谢!

1 个答案:

答案 0 :(得分:3)

可以使用内置slice

为切​​片对象指定名称
  

class slice(start, stop[, step])

     

返回表示由range(start, stop, step)指定的索引集的切片对象。

>>> my_indices = slice(1, 3)
>>> "hello"[my_indices]
'el'

文字切片实际上是在幕后转换为切片对象。这些与range个对象的不同之处在于它们不可迭代。它们只封装了应该切割序列的逻辑:

class D(object):
    def __getitem__(self, x):
        return x

print(D()[1])
# 1              
print(D()[1:3])
# slice(1, 3, None)