作者angleevil (朦胧寻光)
看板Python
标题[问题] 如何将list,string 转成个别的tuple元素
时间Tue Aug 1 14:04:58 2017
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://webptt.com/cn.aspx?n=bbs/Python/M.1501567505.A.5D7.html
1F:→ bibo9901: 判断一下 len(args) 就好了 08/01 14:09
2F:→ angleevil: 但是[1, 2, 0, 3, 4] 或 "hello"要怎麽parser各别元素 08/01 15:02
3F:→ angleevil: list_args = [] 08/01 15:03
4F:→ angleevil: list_args = [list(item) for item in args] 并没有预 08/01 15:03
5F:→ angleevil: 期的功能 08/01 15:04
6F:→ djshen: Unpacking Argument Lists 08/01 15:39
7F:→ bibo9901: 1. parser 是名词, parse 才是动词, 08/01 16:31
8F:→ 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
9F:→ djshen: max(*[1, 2, 0, 3, 4]), min(*"hello")不就可以了? 08/01 18:31
10F:→ djshen: 抱歉 没看到是要实作 08/01 18:38
11F:→ pmove: tuple([1,2,0,3,4])和tuple("hello") ? 08/01 21:56
12F:推 rexyeah: 原po是想自己实做那个function 08/07 14:21