序列步长是负数,是怎么输出这样的值呢?

18妹 2014-07-17 06:23:15
今天看书看到python序列里面的一个函数
number=[1,2,3,4,5,6,7,8,9,10]


print number[8:3:-1]#输出[9, 8, 7, 6, 5]
print number[10:0:-2]#输出10, 8, 6, 4, 2]


求解,步长是负数时候,老理解不了,为什么会是这样的结果?
...全文
555 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
panghuhu250 2014-08-17
  • 打赏
  • 举报
回复
引用 6 楼 maniachhz 的回复:
我想请教你是如何复制出ipython 里运行指令输出的内容?
copy/paste. ipython GUI是qtconsole。
maniachhz 2014-08-17
  • 打赏
  • 举报
回复
引用 7 楼 panghuhu250 的回复:
[quote=引用 6 楼 maniachhz 的回复:] 我想请教你是如何复制出ipython 里运行指令输出的内容?
copy/paste. ipython GUI是qtconsole。[/quote] 原来如此. 难怪我一直复制不了!
maniachhz 2014-08-16
  • 打赏
  • 举报
回复
引用 2 楼 panghuhu250 的回复:
这个解释最接近:http://stackoverflow.com/a/9923354/49117,但没考虑start太大的情况:

In [48]: a
Out[48]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [49]: a[11:0:-2]
Out[49]: [10, 8, 6, 4, 2]

In [50]: a[10:0:-2] # ??? 我以为会返回[9, 7, 5, 3, 1]
Out[50]: [10, 8, 6, 4, 2]
好象start太大时,会从最后一个元素开始。
我想请教你是如何复制出ipython 里运行指令输出的内容?
疯狂的球球ww 2014-08-05
  • 打赏
  • 举报
回复
倒序来看 3楼正解
The_Third_Wave 2014-08-05
  • 打赏
  • 举报
回复
当理解不了时,我一般先记住怎么用,用着用着或许就明白了。请看切片的document
引用
slice(start, stop[, step]) Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
[::]和slice函数式类似的。
  • 打赏
  • 举报
回复
print number[8:3:-1] #相当于遍历这样的索引列表 >>> range(8,3,-1) [8, 7, 6, 5, 4] 那么就是从 number[8], number[7],....number[4] ------- 切片操作符在python中的原型是 [start:stop:step] 即:[开始索引:结束索引:步长值] 开始索引:同其它语言一样,从0开始。序列从左向右方向中,第一个值的索引为0,最后一个为-1 结束索引:切片操作符将取到该索引为止,不包含该索引的值。 步长值:默认是一个接着一个切取,如果为2,则表示进行隔一取一操作。步长值为正时表示从左向右取,如果为负,则表示从右向左取。步长值不能为0 切片的过程是从第一个想要的对象开始,一步步进行的,所以步长为负数,且起始值大于列表总长度时,默认从列表最后开始。 ------- 所以print number[10:0:-2]#输出[10, 8, 6, 4, 2] 相当于print number[9:0:-2] >>> range(9,0,-2) #即遍历这个索引列表对应在 number中的值 [9, 7, 5, 3, 1]
panghuhu250 2014-07-17
  • 打赏
  • 举报
回复
这个解释最接近:http://stackoverflow.com/a/9923354/49117,但没考虑start太大的情况:

In [48]: a
Out[48]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [49]: a[11:0:-2]
Out[49]: [10, 8, 6, 4, 2]

In [50]: a[10:0:-2] # ??? 我以为会返回[9, 7, 5, 3, 1]
Out[50]: [10, 8, 6, 4, 2]
好象start太大时,会从最后一个元素开始。
bugs2k 2014-07-17
  • 打赏
  • 举报
回复
貌似 step 为负数,表示从数组尾部开始计算;first、last 都是从尾部开始计算的

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧