Explain pythonic table[n:m] where m does not mean x-th element
I do this mistake again and again, range(3)[1:2]
does not return [1,2]
but [1]
. Could some开发者_Go百科one explain the logic twist here? Why are m and n not referring to x-th element with the same logic?
Slices and ranges are a pair of numbers: the first element to include, and then the first element not to include. By doing this, you get a few nice benefits. First, the length of the slice is end-start. Second, the slices [x:y] and [y:z] will fit nicely together without duplicating y.
A recent thread challenging this design on Python-Ideas: http://mail.python.org/pipermail/python-ideas/2010-October/008187.html
Edsger Dykstra wrote about this in his inimitable style: http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF , which also covers why the first element is [0].
Here is a citation from Python's tutorial:
s = 'HelpA'
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
As you can see, every character of the string starts at a certain position. So,
>>> s[1:2]
>>> 'e'
# Because 'e' starts at position 1 and ends at position 2:
+---+
| e |
+---+
1 2
The same logic comes with with the range()
function.
There's no logic twist; the second value in a slice indicates the stop index, not the last index. range
uses the same semantics:
>>> range(1, 5)
[1, 2, 3, 4]
>>> range(5)[1:5]
[1, 2, 3, 4]
This way len(range(a, b)) == b - a
.
精彩评论