使用递归的嵌套列表的最高和最低值 [英] Highest and lowest value of nested lists using recursion

查看:45
本文介绍了使用递归的嵌套列表的最高和最低值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用嵌套列表的列表.然后通过使用递归打印列表中索引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.

这篇关于使用递归的嵌套列表的最高和最低值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆