问题描述
在下面的例子中:
foo = ['red', 'white', 'blue', 1, 2, 3]
where: foo[0:6:1]
将打印 foo 中的所有元素.但是,foo[6:0:-1]
将省略第 1 个或第 0 个元素.
我知道我可以使用 foo.reverse() 或 foo[::-1] 来反向打印列表,但我试图理解为什么 foo[6:0:-1] 不打印整个列表?
切片符号简写:
[ :<要排除的第一个元素>:<步骤>]
如果要在反转列表时包含第一个元素,请将中间元素留空,如下所示:
foo[::-1]
您还可以在此处找到一些关于 Python 切片的一般信息:
解释 Python 的切片符号
in the following example:
foo = ['red', 'white', 'blue', 1, 2, 3]
where: foo[0:6:1]
will print all elements in foo. However, foo[6:0:-1]
will omit the 1st or 0th element.
>>> foo[6:0:-1]
[3, 2, 1, 'blue', 'white']
I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?
Slice notation in short:
[ <first element to include> : <first element to exclude> : <step> ]
If you want to include the first element when reversing a list, leave the middle element empty, like this:
foo[::-1]
You can also find some good information about Python slices in general here:
Explain Python's slice notation
这篇关于使用切片表示法反转列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!