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

时间:2018-09-30 10:01:04

标签: python list recursion

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

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

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:])

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

>>> print_tree(lst)
10 
1

3 个答案:

答案 0 :(得分:1)

这里有一种方法,只需一次通过即可编写代码,无需外部库或python的min/max

def high_low(list_or_number):
    if isinstance(list_or_number, list):
        current_min = float('inf')
        current_max = float('-inf')
        for x in list_or_number:
            x_max, x_min = high_low(x)
            if x_max > current_max:
                current_max = x_max
            if x_min < current_min:
                current_min = x_min
        return (current_max, current_min)
    else:
        return (list_or_number, list_or_number)

例如:

>>> high_low([1, 5, [7, 10, [[12, 16], -10]]])
(16, -10)
>>> high_low(3)
(3, 3)
>>> high_low([3,4,5])
(5, 3)

答案 1 :(得分:0)

这可以使用类似的经典问题解决方法(Flatten an irregular list of lists)来实现,无需重新发明轮子,只需使用一些工作方法和后期处理即可:

展开列表列表,然后取最小值和最大值。

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

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

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元素,因此不会产生不必要的内存分配。

答案 2 :(得分:-1)

您可以使用以下递归函数返回当前列表中各项的最大值和最小值以及子列表的最大值和最小值:

def high_low(l):
    try:
        l.extend(high_low(l.pop()))
    except AttributeError:
        return [l]
    except IndexError:
        return []
    return max(l), min(l)

这样:

lst = [1, 5, [7, 10, []]]
print(high_low(lst))

输出:

(10, 1)
相关问题