python让列表倒序输出


想请问下python中用下面的语法就可以让一个list倒序


 list = [1, 2, 3, 4, 5, 6]
print list[::-1]

想请问下其中是什么道理吗,还是就是一种特定用法记住就好了

python flask web.py django tornado

SakiNya 10 years, 8 months ago

list的切片有三个参数:起点,终点,步长

list[::-1] 相当于起点为最后的一个,终点为第一个,然后一次减少一个

更多的看下面的测试


 >>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a.reverse()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[5::-1]
[5, 4, 3, 2, 1, 0]
>>> a[:5:-1]
[9, 8, 7, 6]
>>> a[5:1:-1]
[5, 4, 3, 2]

喵了个咪的吖 answered 10 years, 8 months ago

Your Answer