Python 用谓词递归定义映射

Python 用谓词递归定义映射,python,recursion,Python,Recursion,我想定义一个映射函数,如果元素满足谓词,它将映射到列表的元素上 我的想法是将列表分成两半,然后递归地应用函数。捕获基数是当列表中只剩下1个元素时,如果prae(element)=True、True->fun(x)和False->pass,则将检查该元素。然后,我将连接两个部分以获得最终列表 def is_odd(n): return n%2 == 1 def square(x): return x**2 def map_ifr(lis,prae,fun): if len(lis)

我想定义一个映射函数,如果元素满足谓词,它将映射到列表的元素上

我的想法是将列表分成两半,然后递归地应用函数。捕获基数是当列表中只剩下1个元素时,如果
prae(element)=True
、True->
fun(x)
和False->
pass
,则将检查该元素。然后,我将连接两个部分以获得最终列表

def is_odd(n):
  return n%2 == 1

def square(x):
  return x**2

def map_ifr(lis,prae,fun):
  if len(lis) == 1:
      results = [fun(x) for x in lis if prae(x) == True]
  else:
    mid = len(lis)//2
    first_half = lis[:mid]
    second_half = lis[mid:]
    map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)

a = map_ifr([1 , 2 , 3 , 4 , 5 , 6 ], is_odd , square )
a

操作数类型为
Nonetype
时出错。我不知道为什么会这样。我经常遇到
Nonetype
的问题,不知道真正的原因。感谢您的帮助

您没有从
map\u ifr
函数返回任何内容,因此默认情况下它返回
None
,并在
map\u ifr(前半部分,prae,fun)+map\u ifr(后半部分,prae,fun)
行失败,因为
None+None
不是有效的操作。更正代码:

def map_ifr(lis, prae, fun):
  if len(lis) == 1:
      results = [x for x in lis if prae(x) == True]
  else:
      mid = len(lis)//2
      first_half = lis[:mid]
      second_half = lis[mid:]
      results = map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)

  return results

a = map_ifr([1 , 2 , 3 , 4 , 5 , 6 ], is_odd , square)
print(a)
输出:

[1,3,5]


您不从
map\u ifr
函数返回任何内容,因此默认情况下它返回
None
,并在
map\u ifr(前半部分,prae,fun)+map\u ifr(后半部分,prae,fun)
行失败,因为
None+None
是无效的操作。更正代码:

def map_ifr(lis, prae, fun):
  if len(lis) == 1:
      results = [x for x in lis if prae(x) == True]
  else:
      mid = len(lis)//2
      first_half = lis[:mid]
      second_half = lis[mid:]
      results = map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)

  return results

a = map_ifr([1 , 2 , 3 , 4 , 5 , 6 ], is_odd , square)
print(a)
输出:

[1,3,5]


map\u ifr
不返回任何内容。然而,在Python中,它意味着返回
None
。因此,这里:

map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)
…您试图添加
None+None
,这显然毫无意义,因此您得到了错误

谈到基本情况:

if len(lis) == 1:
    results = [x for x in lis if prae(x) == True]
这会浪费计算能力,因为它会构建列表,然后在函数返回时立即将其丢弃。您应该从函数中返回内容:

def map_ifr(lis,prae,fun):
  if len(lis) == 1:
      return [x for x in lis if prae(x) == True]
  else:
    mid = len(lis)//2
    first_half = lis[:mid]
    second_half = lis[mid:]
    return map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)

map\u ifr
不返回任何内容。然而,在Python中,它意味着返回
None
。因此,这里:

map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)
…您试图添加
None+None
,这显然毫无意义,因此您得到了错误

谈到基本情况:

if len(lis) == 1:
    results = [x for x in lis if prae(x) == True]
这会浪费计算能力,因为它会构建列表,然后在函数返回时立即将其丢弃。您应该从函数中返回内容:

def map_ifr(lis,prae,fun):
  if len(lis) == 1:
      return [x for x in lis if prae(x) == True]
  else:
    mid = len(lis)//2
    first_half = lis[:mid]
    second_half = lis[mid:]
    return map_ifr(first_half,prae,fun) + map_ifr(second_half,prae,fun)