1. 程式人生 > >python 高階函數:sorted(排序)

python 高階函數:sorted(排序)

span ESS ali The nal itl iterable style margin

格式:

sorted(list) / sorted(list, 函數)


官網解釋:

  • sorted(iterable[, cmp[, key[, reverse]]])

  • Return a new sorted list from the items in iterable. #返回一個排序過的新的可叠代的列表


官網給出的詳細sorted用法:

https://docs.python.org/2/howto/sorting.html#sortinghowto



#default

ls = ['You', 'can', 'Do', 'that'];

print sorted(ls);

技術分享圖片


#self

def cmp(s1, s2):
u1 = s1.upper(); #upper 將所有字符串轉為大寫 ----> lower 將所有字符串轉為小寫
u2 = s2.upper();
if u1 < u2:
return -1;
if u1 > u2:
return 1;
return 0;

print sorted(ls, cmp)

技術分享圖片

python 高階函數:sorted(排序)