Min and Max

來源:互聯網
上載者:User

標籤:blog   使用   io   資料   for   ar   代碼   div   

Min and Max

需要處理不同資料類型; 另外*args, 表示的是位置參數, *kwargs表示的是key參數, args的類型為tuple類型, 參數為min(3, 2)時, args為(3, 2), 參數為min([3, 2])時, args為([3, 2], );

列表解析為[i for i in range(0, 1)], 而(i for i in range(0, 1))為generator, 通過.next()屬性擷取下一個元素, 它不像列表解析一次性產生所有元素, 每次調用next產生一個元素;

 

 1 def min(*args, **kwargs): 2     key = kwargs.get("key", None) 3  4     sort_source = args if len(args) > 1 else args[0] #tuple comprehension 5  6     if isinstance(sort_source, set): 7         rel = sort_source.pop() 8     elif type(sort_source) == type((i for i in range(0, 1))): 9         rel = sort_source.next()10     else:11         rel = sort_source[0]12 13     if key != None:14         for each in sort_source:15             if key(each) < key(rel):16                 rel = each17     else:18         for each in sort_source:19             if  each < rel:20                 rel = each21 22     return rel

 

觀摩Cjkjvfnby的代碼

 1 def get_first_from_sorted(args, key, reverse): 2     if len(args) == 1: 3         args = iter(args[0]) 4     return sorted(args, key=key, reverse=reverse)[0] 5   6   7 def min(*args, key=None): 8     return get_first_from_sorted(args, key, False) 9  10  11 def max(*args, key=None):12     return get_first_from_sorted(args, key, True)

無他, 在len(arg) == 1的情況, 仍然需要提取出實際的對象, 如([1, 2], )中的[1, 2]; 高明的地方在於使用了sorted, 省去了自己判斷類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.