递归查找列表列表中的最小值

时间:2020-08-08 05:05:52

标签: python list loops recursion

我正在做一个函数,必须递归地在列表列表中找到最小值。例如,包含[1、2、3,[4、5]]的列表将返回1。

我已经写了一些代码。但是,我不知道如何遍历列表并将最低的数字与列表进行比较。

我在以下代码中添加了注释,该注释使我的函数出错: def recMin(nestedLis):

lowest = 1000000

if len(nestedLis) < 2:
    return nestedLis
else:
    # This function works until it hits a list in a list (ex. [1, 2])
    # because it cannot compare a list to an int. I don't know how to fix this
    if nestedLis[0] < lowest:
        lowest = nestedLis[0]
        print(lowest)
    return lowest + recMin(nestedLis[1:])

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我相信这可以满足您的需求。

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

new_list = list(flatten(lst))
print(max(new_list))

这是来自这篇文章:Highest and lowest value of nested lists using recursion