python 中列表的排序、逆转
001、排序
a、
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> test.sort() ## 直接在原始列表中排序 >>> test [2, 3, 5, 8, 9]
>>> test = [8, 2, 5, 9, 3] >>> test.sort(reverse = True) ## 逆向排序 >>> test [9, 8, 5, 3, 2]
b、
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> sorted(test) ## 不再原始列表中排序 [2, 3, 5, 8, 9] >>> test [8, 2, 5, 9, 3]
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> sorted(test, reverse = True) ## 逆向排序 [9, 8, 5, 3, 2] >>> test [8, 2, 5, 9, 3]
002、逆转
a、
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> test.reverse() ## 在原始列表中逆转 >>> test [3, 9, 5, 2, 8]
b、
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> reversed(test) ## reversed函数逆转 <list_reverseiterator object at 0x7f9b228a59b0> >>> for i in reversed(test): ... print(i) ... 3 9 5 2 8
c、列表切片逆转
>>> test = [8, 2, 5, 9, 3] >>> test [8, 2, 5, 9, 3] >>> test[::-1] ## 列表切片逆转 [3, 9, 5, 2, 8]