python 代码积累

python

  • sort和sorted
    • sort
      • sort basic
      • sort cmp
      • sort key
      • sort reverse
      • sort multi key
    • sorted

sort和sorted

sort

sort basic

sort直接在原来的内存上更改不会返回新的列表

listA = [1, 3, 6, 3, 2]
newList_1 = listA.sort()
print(listA)
print(newList_1)

输出结果

[1, 2, 3, 3, 6]
None

sort cmp

list1=[("8.jpg", 'Logan', 20), ("10.jpg", 'Mike', 22), ("5.jpg", 'Lucy', 19)]
list1.sort(cmp=lambda x, y: cmp(x[0], y[0]))
list1.sort(cmp=lambda x, y: cmp(int(x[0][:-4]), int(y[0][:-4])))
[('10.jpg', 'Mike', 22), ('5.jpg', 'Lucy', 19), ('8.jpg', 'Logan', 20)]
[('5.jpg', 'Lucy', 19), ('8.jpg', 'Logan', 20), ('10.jpg', 'Mike', 22)]

sort key

 list1.sort(key=lambda x:x[0])
 list1.sort(key=lambda x:int(x[0][:-4]))

sort reverse

list1.sort(key=lambda x:int(x[0][:-4]), reverse=True)

sort multi key

按key的顺序排序

list1=[("8.jpg", 'Logan', 20), ("5.jpg", 'Mike', 22), ("5.jpg", 'Lucy', 19)]
list1.sort(key=lambda x:(int(x[0][:-4]),x[2]), reverse=False)
[('5.jpg', 'Lucy', 19), ('5.jpg', 'Mike', 22), ('8.jpg', 'Logan', 20)]

sorted

sorted则相反不会改变原来的列表而是返回新的数据

listA = [1, 3, 6, 3, 2]
newList_2 = sorted(listA)
print(newList_2)
print(listA)
[1, 2, 3, 3, 6]
[1, 3, 6, 3, 2]

你可能感兴趣的:(python,python)