Python,使用 slice() 对象获取最后一个元素

标签 python slice

如何创建一个 slice() 对象,以便它包含列表/字符串的最后一个元素

s = 'abcdef'
s[slice(2,4)]

工作正常。
假设我想获取从第二个到最后的元素,相当于 s[2:]

s[slice(2)]      # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)]     # same as above
s[slice(2, -1)]  # gives a range from second to the end excluding the last element
s[slice(2, 0)]   # gives empty as expected,  since end of range before the start

我可以使用 slice(-1, -2, -1) 专门获取最后一个元素,这对于多个元素将无法正常工作。

最佳答案

如果您想包含最后一个元素,可以通过以下两种方式实现:

s[slice(2,6)]

或用 len 替换 6

或者你也可以这样做:

s[slice(2,None)]

关于Python,使用 slice() 对象获取最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56648242/

相关文章:

arrays - 将 [32]byte 转换为 [8]uint32

javascript - slice 在我的阵列上没有按预期工作

python - 我如何使用 opencv python 根据其位置生成检测到的对象的热图

python - 用于导出 C++ 的 vgg16 keras 保存模型

python - 来自太阳的运动检测照明

python - 如何每 3 个索引切片一个字符串?

python - Matplotlib cmap 未按预期工作

python - 停止运行脚本后是否可以自动关闭正在使用的端口?

python - 每 12 个值计算中位数

amazon-web-services - HITLayoutParameters如何填写