[問題] 如何將list,string 轉成個別的tuple元素(已解決)

看板Python作者 (朦朧尋光)時間8年前 (2017/08/01 14:05), 8年前編輯推噓1(1011)
留言12則, 5人參與, 最新討論串1/2 (看更多)
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

08/01 14:09, , 1F
判斷一下 len(args) 就好了
08/01 14:09, 1F

08/01 15:02, , 2F
但是[1, 2, 0, 3, 4] 或 "hello"要怎麼parser各別元素
08/01 15:02, 2F

08/01 15:03, , 3F
list_args = []
08/01 15:03, 3F

08/01 15:03, , 4F
list_args = [list(item) for item in args] 並沒有預
08/01 15:03, 4F

08/01 15:04, , 5F
期的功能
08/01 15:04, 5F

08/01 15:39, , 6F
Unpacking Argument Lists
08/01 15:39, 6F

08/01 16:31, , 7F
1. parser 是名詞, parse 才是動詞,
08/01 16:31, 7F

08/01 16:32, , 8F
2. if len(args) == 1: args = args[0] 底下不用改
08/01 16:32, 8F
※ 編輯: 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

08/01 18:31, , 9F
max(*[1, 2, 0, 3, 4]), min(*"hello")不就可以了?
08/01 18:31, 9F

08/01 18:38, , 10F
抱歉 沒看到是要實作
08/01 18:38, 10F

08/01 21:56, , 11F
tuple([1,2,0,3,4])和tuple("hello") ?
08/01 21:56, 11F

08/07 14:21, , 12F
原po是想自己實做那個function
08/07 14:21, 12F
文章代碼(AID): #1PW1eHNN (Python)
文章代碼(AID): #1PW1eHNN (Python)