Discuss / Python / 发现一个“神奇”问题,分享下~~

发现一个“神奇”问题,分享下~~

Topic source

1、首先reduce引用的函数f,必须是两个,如果不是两个,编译时会直接报错。 2、再是reduce引用的列表,列表成员至少2个,reduce才会正常执行。 2.1当列表成员个数为0时,程序报错。 2.2当列表成员个数为1时,程序不会报错,但reduce没有正常运行!!这是一个大坑!!它只会把该成员原样输出,根本不会调用函数f!!

为了说明第二点,可以看以下程序:

from functools import reduce
def f(x,y):
  r = x*10 + y*10
  return int(r)

def f1(L):
  return reduce(f,L)

ff = f1('3')
print(ff,'-->',type(ff))

ff = f1('13')
print(ff,'-->',type(ff))

templ = []
templ.append(1.0)
ff = f1(templ)
print(ff,'-->',type(ff))

ff = f1([])
print(ff,'-->',type(ff))

运行结果:只有第二个,列表成员为2的是正常输出:

3 --> <class 'str'>
11111111113333333333 --> <class 'int'>
1.0 --> <class 'float'>
Traceback (most recent call last):
  File "E:/python_pri/测试一个神奇的事情.py", line 20, in <module>
    ff = f1([])
  File "E:/python_pri/测试一个神奇的事情.py", line 7, in f1
    return reduce(f,L)
TypeError: reduce() of empty sequence with no initial value

  • 1

Reply