【问题标题】:Highest and lowest value of nested lists using recursion使用递归的嵌套列表的最大值和最小值
【发布时间】:2019-03-05 17:16:55
【问题描述】:

我想接收一个带有嵌套列表的列表。然后通过递归打印列表中索引 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

【问题讨论】:

    标签: python list recursion


    【解决方案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)
    

    【讨论】:

    • 看起来不错。但是我希望它适用于不同的情况,而不仅仅是一个。
    • 好的,我很难理解它是如何工作的。问题是,它没有。
    • @Blueshirt 在哪些情况下不起作用?你能用这种情况更新你的问题吗?
    • print(high_low([3,5]))print(high_low([3,[5, 7]])) 例如。
    • @EricDuminil 我明白了。我已经为这些情况修复了它。
    【解决方案2】:

    这里有一种可能只写一次代码,不需要外部库或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)
    

    【讨论】:

      【解决方案3】:

      这可以通过类似的经典问题解决(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 元素,因此不会分配不必要的内存。

      【讨论】:

        猜你喜欢
        • 2019-12-18
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 2016-05-07
        • 2020-08-27
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        相关资源
        最近更新 更多