python - 递归地展平具有低指针和高指针的嵌套整数列表
问题描述
我已经看到一些答案将嵌套的整数列表(第一个代码片段)展平,并将列表作为唯一参数:flatten(lst)
. 我的任务是做同样的事情,但有两个指数(低 <= 高)表示要考虑的指数范围:flatten(lst, low, high)
.
带一个参数的工作代码
def flatten(lst):
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
我用打印语句测试了我的代码并且展平过程是正确的,问题是我不确定如何将所有单个值放回列表中以返回它。希望这是有道理的,我不确定还有什么可以尝试的。先感谢您!
我的代码
def flatten(lst, low, high):
if low > high:
return lst
elif isinstance(lst[low], list):
return flatten(lst[low], 0, len(lst[low]) - 1) + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)
else:
return lst[:low] + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)
这就是我用来测试我的代码的东西。
print(flatten([[1, 2], 3, [4, [5, 6, [7], 8]]], 0, 2))
解决方案
您可以按原样使用带有下标赋值的原始函数:
def flatten(lst):
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
L = [[1, 2], 3, [4, [5, 6, [7], 8]]]
L[0:2] = flatten(L[0:2])
print(L)
[1, 2, 3, [4, [5, 6, [7], 8]]]
或者实现一个使用第一个函数的新函数:
def flattenRange(L,low,high):
L = L.copy()
L[low:high] = flatten(L[low:high]) # use high+1 if it is inclusive
return L
甚至是“混蛋”……我的意思是“增强”原作:
def flatten(lst,low=0,high=None):
if low>0 or high is not None:
lst = lst.copy()
lst[low:high] = flatten(lst[low:high]) # use high+1 if it's inclusive
return lst
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
推荐阅读
- python - 打印带有字典/列表的字符串时,如何防止括号和引号被打印出来?
- c++ - 蓝图不影响其父级 - 虚幻引擎
- django - 如果有多个值,则在 .values_list 时排除对象
- angular - node_modules/rxjs/internal/types.d.ts 中的角度错误
- c# - 如何反序列化具有来自不同类的对象的 JSON 字符串?
- r - 替换高频数据中的值
- python - Google Cloud Run - 如何设置“Access-Control-Allow-Origin”标头?
- python - QScintilla 中的 Pygments
- jenkins - 如何在不掩盖 withCredentials.usernamePassword 中的 PASSWORD 的情况下重用 Jenkins 凭据?
- python - 使用类将整数列出为字符串