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" <