使用切片符号反转列表 [英] Reversing a list using slice notation
本文介绍了使用切片符号反转列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下示例中:
foo = ['red', 'white', 'blue', 1, 2, 3]
其中:foo[0:6:1]
将打印foo中的所有元素.但是,foo[6:0:-1]
将省略第1或第0个元素.
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']
我知道我可以使用foo.reverse()或foo [::-1]来反向打印列表,但是我试图理解为什么foo [6:0:-1]不打印整个列表?
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?
推荐答案
切片符号简称:
[ <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]
您还可以在此处找到有关Python切片的一些很好的信息:
解释Python的切片符号
You can also find some good information about Python slices in general here:
Explain Python's slice notation
这篇关于使用切片符号反转列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文