为什么这个列表切片在 Python 中将 0 和 1 视为相同? [英] Why is this list slice treating 0 and 1 as the same in Python?
问题描述
我对切片列表和此处的编号有点困惑.
Python 倾向于从 0 而不是 1 开始,下面显示它以这种方式工作得足够好.但是如果我们从 0 开始,一直到 3,为什么我没有得到 exam
而不是 exa
?毕竟,0 - 3 是 4 个数字.
这是一种有意的方式,最后一个元素是独占的.
为什么会这样?
首先,我的理解是因为 test[0:len(test)]
应该打印所有列表,然后 test[0:len(test)-1]
排除一个元素.这比包含最后一个元素更漂亮、更易读.
其次,是因为如果你有test[:-1]
,它会返回所有元素,但最后一个,非常直观.如果它包含第二个索引,则要剪切最后一个元素,您必须执行 test[:-2]
这很丑陋且难以阅读...
此外,结果列表的长度是 end - start
,这是另一个方便的功能.
I'm a bit confused about slicing a list and the numbering here.
Python tends to start from 0 instead of 1, and it's shown below to work in that way well enough. But if we're starting from 0, and going until 3, why am I not getting exam
instead of exa
? After all, 0 - 3 is 4 numbers.
>>> test = "example string"
>>> print test[:3]
exa
>>> print test[0:3]
exa
>>> print test[1:3]
xa
This is an intentional way, last element is exclusive.
Why is it so?
Firstly, my understanding it is because test[0:len(test)]
should print all the list and then test[0:len(test)-1]
excludes one element. This is prettier and more readable than if the last element would be included.
Secondly, it is because if you have test[:-1]
it will return all the elements, but the last, which is very intuitive. If it would include the second index, to cut the last element you'd have to do test[:-2]
which is ugly and makes it harder to read...
Also, length of your resulting list is end - start
, which is yet another convenient feature about it.
这篇关于为什么这个列表切片在 Python 中将 0 和 1 视为相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!