【问题标题】:Finding the lowest value in a list of lists recursively [duplicate]递归查找列表列表中的最小值[重复]
【发布时间】:2020-11-28 09:28:40
【问题描述】:

我正在创建一个函数,我必须递归地在列表列表中找到最小值。例如,包含 [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:])

任何帮助将不胜感激!

【问题讨论】:

    标签: python list loops recursion


    【解决方案1】:

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

    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

    【讨论】:

    • 你应该投票关闭这个作为重复,而不是从另一个答案重新发布
    • 哦,我对 stackoverflow 并不完全熟悉,但我不这样做
    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 2020-11-03
    • 2018-06-13
    • 2013-03-17
    • 2019-12-18
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多