关于使用高阶函数,把str转换为int的函数
>>> from functools import reduce>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits
...
>>> reduce(fn, map(char2num, '13579'))
13579
请问下第二个函数是干嘛用的呢? 单独调用char2num(s)这个函数也会出错呀。
>>> def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits
>>> char2num(2)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
char2num(2)
File "<pyshell#23>", line 3, in char2num
return digits
KeyError: 2
因为你调用错了,这是个将字符串转为int的函数,参数一个是字符串,而你传递进去的是int数组
应该写成 char2num('2') sunrise085 发表于 2020-8-18 00:03
因为你调用错了,这是个将字符串转为int的函数,参数一个是字符串,而你传递进去的是int数组
应该写成
>>> char2num('11')
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
char2num('11')
File "<pyshell#23>", line 3, in char2num
return digits
KeyError: '11'
再请问下,char2num(s),实参应该是传digits这个字典的键,是这样理解么?所以传'11'也不行。 dong811019 发表于 2020-8-18 00:12
>>> char2num('11')
Traceback (most recent call last):
File "", line 1, in
不知道哪来的线条{:10_257:} 相当于自己写str转int的函数,
>>> def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits
首先,自定义函数char2num传入str(其实就是你输入的数字),将你传入的str作为key,然后通过digits字典返回int类型的值,从而达到str转int的目的。
所以你在单独调用该函数时,不能传入数字2,而必须是字符串'2',既带引号的。因为字典中的key都是字符串格式,所以会有你的报错。
dong811019 发表于 2020-8-18 00:12
>>> char2num('11')
Traceback (most recent call last):
File "", line 1, in
你的这个函数中的字典键值只有'0'到'9'
你传入'11'当然会报错说键值错误啦!
只能传进去 '0' 到 '9' 最后的育碧
页:
[1]