【问题标题】:why slice operator in below case doesn't work in python? [duplicate]为什么以下情况下的切片运算符在 python 中不起作用? [复制]
【发布时间】:2019-10-08 00:17:45
【问题描述】:

我在看一个python视频,按照导师切片算子的逻辑,有一个case是不行的。

step value can be either +ve or -ve
-----------------------------------------
if +ve then it should be forward direction (L to R)
if -ve then it should be backward direction(R to L)

if +ve forward direction from begin to end-1
if -ve backward direction from begin to end + 1

in forward direction
-------------------------------
default : begin : 0
default : end : length of string
default step : 1

in backward direction
---------------------------------
default begin : -1
default end : -(len(string) + 1)

我尝试在 python idle 上运行状态并得到以下结果:

>>> x = '0123456789'
>>> x[2:-1:-1]
''
>>> x[2:0:-1]
'21'

根据规则,我应该得到'210' 的结果,但我得到的是''

【问题讨论】:

  • 请正确格式化您的问题
  • x[2:-len(x)-1:-1] >>> 210
  • 问题结束后也可以选择答案

标签: python python-3.x


【解决方案1】:

索引2:-1:-1 扩展为2:9:-1。负的开始或停止索引总是扩展到len(sequence) + indexlen('0123456789') + (-1) 是 9。不能以 -1 为步长从 2 到 9,所以结果为空。

相反,使用2::-1 一个空的(或None)停止索引意味着“抓住一切”。当 strep 大小为负时,空停止索引的默认值为-len(sequence) - 1,这也是-(len(sequence) + 1),以抵消停止索引始终排他的事实。

【讨论】:

  • 你能告诉我它是如何扩展到 2:9:-1 的吗??
  • 10-1 = 9。10 是 len('0123456789')。
  • 对不起,我没听懂你,能告诉我你应用的通用规则吗?
  • 我已扩展我的答案以帮助您了解规则。这是一个令人困惑的话题,需要一段时间才能掌握,无需道歉。如果您想进一步澄清,请告诉我。
  • 同样的规则适用。 -19 (len(x) - 1) 和 -64 (len(x) - 6)。现在将其读作x[9:4:-1]。从x[9] 下降到x[5](停止索引是唯一的)你会得到'98765'
猜你喜欢
  • 2017-10-19
  • 2012-12-16
  • 2015-05-26
  • 2013-10-21
  • 2021-06-03
  • 2023-03-18
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
相关资源
最近更新 更多