看板 Python 關於我們 聯絡資訊
hello 各位好, 最近在練習實作max,min的時候,遇到一個型態的問題. 如何把[1, 2, 0, 3, 4]<-list 或 "hello" <-string 處理成個別的tuple元素呢?? 查了型態轉換,string to tuple or list to tuple.一直都無法達到自己想要的. 各位有甚麼建議嘛?? ===================================修改後================================================== import types def min(*args, **kwargs): key = kwargs.get("key", None) print(key) if len(args) == 1: args = args[0] if type(args) == type('a'): MinNo='z' else: MinNo=999 for ii in args: if type(args) == type('a'): if ord(ii) < ord(MinNo): MinNo = ii else: if key == int: if int(ii) < int(MinNo): MinNo = ii else: if ii < MinNo: MinNo = ii return MinNo def max(*args, **kwargs): key = kwargs.get("key", None) if len(args) == 1: args = args[0] if type(args) == type('a'): MaxNo='a' else: MaxNo=-1 for ii in args: if type(args) == type('a'): if ord(ii) > ord(MaxNo): MaxNo = ii else: if key == int: if int(ii) > int(MaxNo): MaxNo = ii else: if ii > MaxNo: MaxNo = ii return MaxNo if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing #assert max(3, 2) == 3, "Simple case max" #assert min(3, 2) == 2, "Simple case min" #assert max([1, 2, 0, 3, 4]) == 4, "From a list" #assert min("hello") == "e", "From string" #assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items" assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key" <----這個要怎麼實作阿?? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.107.139 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1501567505.A.5D7.html
bibo9901: 判斷一下 len(args) 就好了 08/01 14:09
angleevil: 但是[1, 2, 0, 3, 4] 或 "hello"要怎麼parser各別元素 08/01 15:02
angleevil: list_args = [] 08/01 15:03
angleevil: list_args = [list(item) for item in args] 並沒有預 08/01 15:03
angleevil: 期的功能 08/01 15:04
djshen: Unpacking Argument Lists 08/01 15:39
bibo9901: 1. parser 是名詞, parse 才是動詞, 08/01 16:31
bibo9901: 2. if len(args) == 1: args = args[0] 底下不用改 08/01 16:32
※ 編輯: angleevil (59.124.107.139), 08/01/2017 17:06:38 ※ 編輯: angleevil (59.124.107.139), 08/01/2017 17:15:52 ※ 編輯: angleevil (59.124.107.139), 08/01/2017 17:44:35 ※ 編輯: angleevil (59.124.107.139), 08/01/2017 17:53:46
djshen: max(*[1, 2, 0, 3, 4]), min(*"hello")不就可以了? 08/01 18:31
djshen: 抱歉 沒看到是要實作 08/01 18:38
pmove: tuple([1,2,0,3,4])和tuple("hello") ? 08/01 21:56
rexyeah: 原po是想自己實做那個function 08/07 14:21