python-3.x - 编写一个递归函数 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' 的操作数类型不受支持
解决方案
您的代码中有几个错误:
- 在基本情况下,您返回一个 int 和一个函数,即
return 0
andreturn clean_list
。 - 在第三种情况下,您需要连接列表,您正在连接整数和列表
l1[0] + clean_list(l1[1:], l2)
。 - 如果
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]
推荐阅读
- javascript - 如何使用 Android Manifest 将 React Native Android 的默认文本颜色更改为黑色?
- sql - SQL Server 收集最新事务并忽略已选择的事务
- user-experience - 我们是否必须使用 SF Symbols 来设计原生 iOS 应用程序?
- html - HTML水平对齐行内块?
- python - 在机器学习算法中处理数据框中的时间日期特征
- javascript - ExpressJS 给出:解析错误:意外的令牌 =>
- css - 使用 semanti-ui-react 仅在一个网格列中滚动
- code-coverage - 了解 Eclemma 结果
- linux - 在 BASH 中创建更简洁的菜单,而不是简单地向上滚动屏幕
- c# - 扫描和更改像素 c#