使用递归的嵌套列表的最高和最低值

编程入门 行业动态 更新时间:2024-10-24 06:35:18
本文介绍了使用递归的嵌套列表的最高和最低值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用嵌套列表的列表.然后通过使用递归打印列表中索引0或2的最大值和索引0或2的最小值.

I want to take in a list with nested lists. Then print the highest value of index 0 or 2 in the list and the lowest value of index 0 or 2, through using recursion.

这是我到目前为止得到的:

This is what I got so far:

lst = [1, 5, [7, 10, []]] def high_low(my_list): new_lst = [] if not my_list: print max(new_lst) print min(new_lst) elif isinstance(my_list[0], int): return new_lst.append(my_list[0]) + high_low(my_list[2:]) elif isinstance(my_list[0], list): return new_lst.append(max(my_list[0])) + high_low(my_list[2:])

这是我遇到的问题,因为我不知道如何从嵌套列表中获取最高和最低值,然后将其附加到新的空列表中.例如,这就是我希望输出看起来像的样子:

This is where I get stuck, as I don't know how to get the highest and lowest value from a nested list and then append it to the new empty list. For example this is what I want the output to look like:

>>> print_tree(lst) 10 1

推荐答案

这可以使用类似的&经典的问题解决方法(将不规则的列表弄平),无需重新发明轮,只需使用一些工作方法和后处理:

this can be achieved using a similar & classic problem solving (Flatten an irregular list of lists), no need to reinvent the wheel, just use some working method & post-process:

展平列表列表,然后取 min &最多.

Flatten the list of lists, then take min & max of it.

import collections def flatten(l): # function copied from the link above for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el lst = [1, 5, [7, 10, []]] new_list = list(flatten(lst)) # create a list cos we'll be iterating twice on it print(max(new_list)) print(min(new_list))

结果

10 1

通过手动循环进行一次迭代:

with one iteration with a manual loop:

min_value = None max_value = None for v in flatten(lst): if min_value is None or v < min_value: min_value = v if max_value is None or v > max_value: max_value = v print(min_value) print(max_value)

flatten 方法很不错,因为它不会创建临时的 list 元素,因此不会产生不必要的内存分配.

the flatten method is nice because it doesn't create temporary list elements so no unneccesary memory allocations.

更多推荐

使用递归的嵌套列表的最高和最低值

本文发布于:2023-11-22 20:08:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618833.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   嵌套   低值   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!