首页 > 解决方案 > 编写一个递归函数 clean list(l1, l2),它将两个列表作为输入并返回 l1 中不存在于 l2 中的元素列表

问题描述

def clean_list(l1, l2):
    if l1 == l2:
        return 0
    if l1 == []:
        return clean_list
    if l1[0] not in l2:
        return l1[0] + clean_list(l1[1:], l2)
    else:
        return clean_list(l1[1:], l2)
unique = clean_list([1,2,3,4,5,6,7], [2,4,6])
print(unique)

不断收到错误消息,提示 +: 'int' 和 'function' 的操作数类型不受支持

标签: python-3.x

解决方案


您的代码中有几个错误:

  1. 在基本情况下,您返回一个 int 和一个函数,即return 0and return clean_list
  2. 在第三种情况下,您需要连接列表,您正在连接整数和列表l1[0] + clean_list(l1[1:], l2)
  3. 如果l1为空 ( not l1),则应返回空列表。

话虽这么说,你这里是代码:

def clean_list(l1, l2):
    if l1 == l2:
        return []

    if not l1:
        return []

    if l1[0] not in l2:
        return [l1[0]] + clean_list(l1[1:], l2)
    else:
        return clean_list(l1[1:], l2)


unique = clean_list([1, 2, 3, 4, 5, 6, 7], [2, 4, 6])
print(unique)

输出

[1, 3, 5, 7]

推荐阅读