求助帖,关于Python的切片

apelif 2012-03-18 09:23:31
>>>numbers=[1,2,3,4,5,6,7,8,9,10]
>>>numbers[8:3:-1]
[9, 8, 7, 6, 5]
>>> numbers[:5:-2]
[10, 8]
这两条语句不太懂,谁能给解释下
...全文
188 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
LS已经很清楚了

第一个是从numbers[8] -> numbers[3](不包括numbers[3]), 步长为-1,也就是倒着走

第二个是从number[0]开始,步长为-2,倒着走到numbers[5](不包括numbers[5])

RabbitLBJ 2012-03-19
  • 打赏
  • 举报
回复
1.先看第三个参数,如果该数为正,则从前往后数,如果为负,则从后往前数,如果非1,则是跳步来数
2.PYTHON总是左开右闭的,也就是说第一个参数要包括,第二个参数不包括
3.如果第一个参数没填,则自动设为第一个参数(根据第三个参数的正负判断是整数第一个还是倒数第一个)
4.如果第二个参数没填,则自动设定为最后一个参数(根据第三个参数的正负判断是整数第一个还是倒数第一个,另外这个参数不会包括进去【左开右闭】)
angel_su 2012-03-19
  • 打赏
  • 举报
回复
练练英文自己翻翻手册,The Python Standard Library -> 5.6. Sequence Types 有几个注释:
...
s[i] i‘th item of s, origin 0 (3)
s[i:j] slice of s from i to j (3)(4)
s[i:j:k] slice of s from i to j with step k (3)(5)
...
If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

...
Gloveing 2012-03-18
  • 打赏
  • 举报
回复
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.

37,741

社区成员

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

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