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

作者: angleevil (朦朧尋光)   2017-08-01 17:53:12
感謝大家的幫忙,經過bibo9901和cutekid幫忙. 已解決了
import types
def min(*args, **kwargs):
key = kwargs.get("key", None)
if len(args) == 1:
args = args[0]
it = iter(args) # get an iterator
try:
MinNo = next(it) # take the first value from the iterator
except StopIteration:
raise ValueError("max() called with no values")
?
if key == None:
for ii in it:
if ii < MinNo:
MinNo = ii
else:
min_keyval = key(MinNo) # initialize the minimum keyval
for ii in it:
keyval = key(ii)
if keyval < min_keyval: # compare keyvals, rather than regular values
min_keyval = keyval
MinNo = ii
return MinNo
?
def max(*args, **kwargs):
key = kwargs.get("key", None)
if len(args) == 1:
args = args[0]
it = iter(args) # get an iterator
try:
MaxNo = next(it) # take the first value from the iterator
except StopIteration:
raise ValueError("max() called with no values")
?
if key == None:
for ii in it:
if ii > MaxNo:
MaxNo = ii
else:
max_keyval = key(MaxNo) # initialize the maxmum keyval
for ii in it:
keyval = key(ii)
if keyval > max_keyval: # compare keyvals, great than regular values
max_keyval = keyval
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 18:05:00
def max(*args, key=None):

Links booklink

Contact Us: admin [ a t ] ucptt.com