切片:
>>> bag = range(20) >>> bag [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> for i in range(0, len(bag),3): ... print bag[i:i+3] ... [0, 1, 2] [3, 4, 5] [6, 7, 8] [9, 10, 11] [12, 13, 14] [15, 16, 17] [18, 19]
>>> bag[::-1] #翻转List
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> bag[:10] #取前10个
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bag[-10:] #取后10个
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
排序:
>>> sorted([10,30,50,20,40]) [10, 20, 30, 40, 50] >>> sorted([10,30,50,20,40],reverse=True) [50, 40, 30, 20, 10] >>> students = [('e', 'A', 15), ('f', 'D', 12), ('g', 'B', 10)] >>> print(sorted(students,cmp=lambda x,y : cmp(x[0], y[0]),reverse=False)) [('e', 'A', 15), ('f', 'D', 12), ('g', 'B', 10)] >>> print(sorted(students,cmp=lambda x,y : cmp(x[1], y[1]),reverse=False)) [('e', 'A', 15), ('g', 'B', 10), ('f', 'D', 12)] >>> print(sorted(students,cmp=lambda x,y : cmp(x[2], y[2]),reverse=False)) [('g', 'B', 10), ('f', 'D', 12), ('e', 'A', 15)]