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

作者: angleevil (朦朧尋光)   2017-08-01 14:04:58
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" <
作者: bibo9901 (function(){})()   2017-08-01 14:09:00
判斷一下 len(args) 就好了
作者: angleevil (朦朧尋光)   2017-08-01 15:02:00
但是[1, 2, 0, 3, 4] 或 "hello"要怎麼parser各別元素list_args = []list_args = [list(item) for item in args] 並沒有預期的功能
作者: djshen (djshen)   2017-08-01 15:39:00
Unpacking Argument Lists
作者: bibo9901 (function(){})()   2017-08-01 16:31:00
1. parser 是名詞, parse 才是動詞,2. if len(args) == 1: args = args[0] 底下不用改
作者: djshen (djshen)   2017-08-01 18:31:00
max(*[1, 2, 0, 3, 4]), min(*"hello")不就可以了?抱歉 沒看到是要實作
作者: pmove (金疾檸檬)   2017-08-01 21:56:00
tuple([1,2,0,3,4])和tuple("hello") ?
作者: rexyeah (ccccccc)   2017-08-07 14:21:00
原po是想自己實做那個function

Links booklink

Contact Us: admin [ a t ] ucptt.com