Discuss / Python / 作业3

作业3

Topic source
在此插入代码
def f(x, y):
    return x*10 + y
def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
s1,s2 = s.split('.')
return reduce(f, map(char2num, s1)) + (reduce(f, map(char2num, s2))/pow(10,len(s2)))

chinzen

#2 Created at ... [Delete] [Delete and Lock User]

请问在return中dict后面的这个[s]是什么作用,试了一下如果没有的话程序就会报错。

幻之海洋

#3 Created at ... [Delete] [Delete and Lock User]

通过关键字得到值

Ryan_CL

#4 Created at ... [Delete] [Delete and Lock User]

没太明白你说的,能说的再具体一点吗 ?谢谢~

思路就是用split把123.456切片,把字符串123赋值给s1(整数部分),字符串456给s2(小数部分)。

return reduce(f, map(char2num, s1)) + (reduce(f, map(char2num, s2))/pow(10,len(s2)))

reduce(f, map(char2num, s1))

把类型为str的S1转成类型为int的。

(reduce(f, map(char2num, s2))/pow(10,len(s2))

先进行类型转换,然后除以10的S2长度次方,这里len(s2)显然是3

整句话意思就是123+456/1000=123.456

最后2句是精髓,好好理解消化一下。

坏笑blue

#6 Created at ... [Delete] [Delete and Lock User]

我也觉得这个想法好 from functools import reduce def ks(s):
def f(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def fn(x,y): return 10*x+y def fa(x,y): return x/10+y a=s.find('.') b=int(a) s1=s[:b] s2=s[-1:b:-1] return reduce(fn,map(f,s1))+reduce(fa,map(f,s2))/10

{}是字典,[]是索引,{‘0’:0,....}['0']返回的就是0,这个函数就是这样把字符型转化成int型的。 提问者评价


  • 1

Reply