import functools def cmp(x, y): if x < y: return 1 return -1 a = [1, 20, 4, 50] b = sorted(a, key=functools.cmp_to_key(cmp)) print(b)
自定義cmp,進行排序比較 import functools def cmp(x, y): if x < y: return 1 return -1 a = [1, 20, 4, 50] b =
判斷是否可以迭代,看類中是否有__iter__方法 __iter__方法會自動調用__next__方法,返回下一個對象 from collections import Iterable # 判斷一個類是否可迭代,看有沒__it