Python反向跨步切片 [英] Python reverse-stride slicing

查看:62
本文介绍了Python反向跨步切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题的一个具体例子是,在这个例子中我怎样才能得到‘3210’?"

<预><代码>>>> foo = '0123456'>>> foo[0:4]'0123'>>> foo[::-1]'6543210'>>> foo[4:0:-1] # 我正在为 '3210' 拍摄但犯了一个围栏错误,这很好,但是...'4321'>>> foo[3:-1:-1] # 我怎样才能得到'3210'?''>>> foo[3:0:-1]'321'

我可以写 foo[4:0:-1]、foo[5:1:-1] 等并得到我期望的结果,这似乎很奇怪,但是没有办法写切片,这样我得到'3210'.

一种临时的方法是 foo[0:4][::-1],但这会在此过程中创建两个字符串对象.我将执行此操作数十亿次,因此每个字符串操作都很昂贵.

我一定遗漏了一些愚蠢而简单的东西.感谢您的帮助!

解决方案

简单地排除结束范围索引...

<预><代码>>>>foo[3::-1]'3210'

具有讽刺意味的是,关于我认为您没有尝试过的唯一选择.

A specific example of my question is, "How can I get '3210' in this example?"


>>> foo = '0123456'
>>> foo[0:4]
'0123'
>>> foo[::-1]
'6543210'
>>> foo[4:0:-1] # I was shooting for '3210' but made a fencepost error, that's fine, but...
'4321'
>>> foo[3:-1:-1] # How can I get '3210'?
''
>>> foo[3:0:-1]
'321'

It seems strange that I can write foo[4:0:-1], foo[5:1:-1], etc. and get what I would expect, but there's no way to write the slice so that I get '3210'.

A makeshift way of doing this would be foo[0:4][::-1], but this creates two string objects in the process. I will be performing this operation literally billions of times, so every string operation is expensive.

I must be missing something silly and easy. Thanks for your help!

解决方案

Simply exclude the end range index...

>>> foo[3::-1]
'3210'

Ironically, about the only option I think you didn't try.

这篇关于Python反向跨步切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆