【问题标题】:given a list of list return the list of integer values from the list给定一个列表列表返回列表中的整数值列表
【发布时间】:2019-10-15 00:19:22
【问题描述】:

给定一个列表

lt=[1,2,[3,[5,[6,[7]]]]] 

我知道这是一个基本问题,并且我已经使用 for 循环完成了它,但是我需要了解如何在单行或两行中完成这个基本问题。这是在一次采访中问我的。

return [1,2,3,5,6,7]

【问题讨论】:

  • 你确定只有两行吗?使用递归,您可能只需要两行代码,但随后您必须调用已声明的函数,这将是第三行代码。例如,您会看到 DarryG 的答案,但我们使用三行而不是两行。两行确实 ceclare 函数和调用它。
  • @bencv:是的,事实上这是重复的。 stackoverflow.com/questions/2158395/… 中的解决方案之一仅使用两行(或一行带有';')这是 Statham 的答案。然而,reduce 不再是 python3 中的预声明函数,因此必须在行中添加一些导入

标签: python python-3.x list


【解决方案1】:

使用函数递归地展平。

解决方案

# Custom function
def get_flatlist(l, flat_list=None, no_more_list_elements = True):
    if flat_list is None:
        flat_list = list()

    for x in l:
        if isinstance(x,list):        
            flat_list += x
            no_more_list_elements = no_more_list_elements & False
        else:
            flat_list.append(x)
            no_more_list_elements = no_more_list_elements & True
    #print(no_more_list_elements)
    if not no_more_list_elements:        
        flat_list = get_flatlist(flat_list.copy(), 
                                 flat_list=None, 
                                 no_more_list_elements = True)
    return flat_list    

get_flatlist(lt)

输出

[1, 2, 3, 5, 6, 7]

数据

lt=[1,2,[3,[5,[6,[7]]]]] 

【讨论】:

    【解决方案2】:

    这是@DarrylG 解决方案的修改版本,有助于减少行数。

    flatten = lambda lst: sum((flatten(v) if isinstance(v, list) else [v] for v in lst), [])
    flatten(lt)
    

    Lambda 函数可以是递归的,但比函数声明短一行。

    这也可以通过使用;在一行中

    flatten = lambda lst: sum((flatten(v) if isinstance(v, list) else [v] for v in lst), []) ; flatten(lt) 
    

    【讨论】:

      【解决方案3】:

      扁平化列表的方法(1-2行函数) (Flatten an irregular list of lists 的模组)

      1. 使用生成器创建单个元素列表
      2. 使用 sum 将这些附加到单个列表中

      
      def flatten(lst):
          return sum( ([x] if not isinstance(x, list) else flatten(x)
                       for x in lst), [] )
      
      

      lt=[1,2,[3,[5,[6,[7]]]]]

      print(flatten(lt))

      输出
      [1, 2, 3, 5, 6, 7]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 2022-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-13
        相关资源
        最近更新 更多