简单地排除了最终范围索引...
>>> foo[3::-1]
'3210'
shimit在您的切片符号中的末端索引:
>>> foo = '0123456'
>>> foo[3::-1]
'3210'
>>> first_4_items_reversed = slice(3,None,-1)
>>> foo[first_4_items_reversed]
'3210'
如果您正在寻找比扩展切片符号更可读的东西:
阅读“技术文档”(here
)之后 - 特别是句子:
如果两端是负的,则将序列的长度添加到其中。
>>> foo = '0123456'
>>> foo[3:-1-len(foo):-1]
'3210'
>>>
因此,我认为在编程上确定“终点”的最佳答案是提供一个命名良好的助手功能,这清楚地表明其论点总是被视为积极的偏移,也许是
我认为这种“特殊”案例的清晰度极为重要,因为许多常见用例和重要用例取决于负偏移的默认行为(即增加它们的长度)。 我个人经常使用'-1'终点的意思:停在最后一个元素之前。 ,根据您的评论:
...算法的工作方式如下:foo [i:i-4:-1],从高'i'开始然后走下去。
我可能会做以下内容:
def slice_by_len(data, start, length, step=1):
end = start + length if step > 0 else start - length
if end < 0:
# Fix the negative offset to get what we really want
end -= len(data)
return data[start:end:step]
然后为每个切片打电话:
foo_part = slice_by_len(foo, i, 4, -1)
上面很容易就'i'的值进行循环循环
您可以使用
s[::-1]
来逆转整个字符串。 但是,如果要以一定的固定长度逆转每个子字符串,则可以首先提取子字符串,然后逆转整个子字符串。 例如,让我们假设我们需要检查每个带有字符串长度3的子字符串是一个palindrome,我们可以这样做:
foo
如果您想检查一个子字符串是否是这样的回文:
>>> foo = '0102030'
>>> for i in range(len(foo)-3):
... if foo[i:i+3] == foo[i:i+3][::-1]:
... print(foo[i:i+3], 'is a palindrome')
... else:
... print(foo[i:i+3], 'is not a palindrome')
...
010 is a palindrome
102 is not a palindrome
020 is a palindrome
203 is not a palindrome
030 is a palindrome
您将无法处理if foo[i:i+3] == foo[i+2:i-1:-1]:
...
i
相比0
第一个解决方案的唯一缺点是它使用了更多的内存,但没什么大不了的。
格式:
foo[2:-1:-1]
所需的字符串
foo[2:n-1:-1]
>>> foo = '0123456'
这里是两个通用解决方案:
获取前向切片,然后将其反转:
3210
基于this Answer,在第一个元素之前使用负面步骤,并停止1个元素(加上停止偏移):
结合执行时间,第一个版本更快:
>>> foo[stop_idx:start_idx+1][::-1]
'3210'
在上述解决方案中,您可以做类似的事情:
>>> foo[start_idx:stop_idx-len(foo)-1:-1]
'3210'
>>> a[start_idx:stop_idx-len(a)-1:-1]
[2, 1]
是因为-1中的-1表示最后一个元素。
尽管列表(范围(4,-1,-1))= [4,3,2,1,0],
>>> timeit.timeit('foo[stop_idx:start_idx+1][::-1]', setup='foo="012345"; stop_idx=0; start_idx=3', number=10_000_000)
1.7157553750148509
>>> timeit.timeit('foo[start_idx:stop_idx-len(foo)-1:-1]', setup='foo="012345"; stop_idx=0; start_idx=3', number=10_000_000)
1.9317215870250948