如何创建一个 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/