1 sorted() 能夠對數字,字符串(ASCII)進行排序python
list = [12,3,4,4,3,4,5,5,6,4,6] s = sorted(list) print(s) #[3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 12] # 默認升序排列 # 降序排列 def reveled(x,y): if x < y : return 1 if x > y : return -1 else: return 0 s = sorted(list,reveled) print(s) #[3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 12] [12, 6, 6, 5, 5, 4, 4, 4, 4, 3, 3] 只能在python2 中運行 #字符串的排序 list3 = ['if','With','BOY','Adc','case','sesion','asd'] def char_str(string1,string2): string1 = string1.upper() string2 = string2.upper() if string1 > string2: return 1 if string1 < string2: return -1 else: return 0 s = sorted(list3,char_str) print(s) # ['Adc', 'asd', 'BOY', 'case', 'if', 'sesion', 'With'] # 3 中不能這樣運行