Discuss / Python / 关于高阶函数的一个问题

关于高阶函数的一个问题

关爱苹果

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

在reduce的描述中,您引用了如下的例子函数:

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] ... 但是我执行的时候会报错: In [5]: 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] ...:

In [6]: char2num('123456')

KeyError Traceback (most recent call last)

<ipython-input-6-fea4ce79740e> in <module>() ----> 1 char2num('123456')

<ipython-input-5-5552ea0be1a8> in char2num(s) 1 def char2num(s): ----> 2 return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] 3

KeyError: '123456'

chaif87

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

不能直接使用char2num('123456') 应该使用map函数对'123456'中每个字符进行迭代运行char2num函数,再使用reduce函数对每个经转换后的数字进行累积。原例如下:

>>> def fn(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]

>>> reduce(fn, map(char2num, '13579'))
13579

  • 1

Reply