1. # sort.py
2. # 這個類用來演示如何對自定義物件進行排序
3. class sortobj:
4. a = 0
5. b = ''
6. def __init__(self, a, b):
7. self.a = a
8. self.b = b
9. def printab(self):
10. print self.a, self.b
11.
12. # 演示對字串列表進行排序
13. samplelist_str = ['blue','allen','sophia','keen']
14. print samplelist_str
15. samplelist_str.sort()
16. print samplelist_str
17.
18. print '\n'
19.
20. # 演示對整型數進行排序
21. samplelist_int = [34,23,2,2333,45]
22. print samplelist_int
23. samplelist_int.sort()
24. print samplelist_int
25.
26. print '\n'
27.
28. # 演示對字典資料進行排序
29. sampledict_str =
33. print sampledict_str
34. # 按照key進行排序
35. print sorted(sampledict_str.items(), key=lambda d: d[0])
36. # 按照value進行排序
37. print sorted(sampledict_str.items(), key=lambda d: d[1])
38.
39. # 構建用於排序的類例項
40. obja = sortobj(343, 'keen')
41. objb = sortobj(56, 'blue')
42. objc = sortobj(2, 'aba')
43. objd = sortobj(89, 'iiii')
44.
45. print '\n'
46.
47. samplelist_obj = [obja, objb, objc, objd]
48. # 例項物件排序前
49. for obj in samplelist_obj:
50. obj.printab()
51. print '\n'
52. # 按照物件的a屬性進行排序
53. samplelist_obj.sort(lambda x,y: cmp(x.a, y.a))
54. for obj in samplelist_obj:
55. obj.printab()
56. print '\n'
57. # 按照物件的b屬性進行排序
58. samplelist_obj.sort(lambda x,y: cmp(x.b, y.b))
59. for obj in samplelist_obj:
60. obj.printab()
python中的排序
coding utf 8 from operator import itemgetter a 1,4,3,2,5 b 5,2,3 6,0,1 1,3,2 print sorted a 預設為公升序排序 print sorted a,reverse true reverse為true時,降序排列 pr...
Python中的排序
最近在學習python,想隨便 寫一下,python 寫一些 排序,排序 演算法 那麼多,我也不一一介紹,寫幾個比較簡單的,冒泡,選擇,快排,插入排序 用 python 實現一下,當然 也有參考 網上的寫法,相互學習吧,直接進入正題 氣泡排序 思想 我想大家 都應該理解就是 相鄰 兩個key 進行比...
python中的氣泡排序 Python中的氣泡排序
氣泡排序 bubble sort 也是一種簡單直觀的排序演算法。它重複地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重複地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個演算法的名字由來是因為越小的元素會經由交換慢慢 浮 到數列的頂端。氣泡排序演...