【每日一题0810】扁平列表

:woman_mage:我们的任务是编写一个python函数,接收任意数量的参数,并将它们展开成一个扁平化的列表。如果传入的任何参数是嵌套列表,无论其深度如何,列表中的单个元素将被展平,以便它们与其他参数存在于同一级别。

示例:
输入:1, [2, 3], 4, 5, [6, [7]] ,输出:[1, 2, 3, 4, 5, 6, 7]

题目难度:中等
题目来源:codewars

def flatten(*inp):
    pass
    
assert flatten(1,2,3) == [1,2,3]
assert flatten([1,2],[3,4,5],[6,[7],[[8]]]) == [1,2,3,4,5,6,7,8]
assert flatten(1,2,['9',[],[]],None) == [1,2,'9',None]

仅供参考

flatten_list = []
def flatten(*inp):
    for i in inp:
        if type(i) in [int,str,None] or i == None:
            flatten_list.append(i)
        elif type(i) == list and len(i)>0:
            for j in i:
                flatten(j)
    return list(set(flatten_list))

print(flatten(1, 2, 3))
print(flatten([1, 2], [3, 4, 5], [6, [7], [[8]]]))
print(flatten(1, 2, ['9', [], []], None))

普通青年

def flatten(*inp):
    
    result = []
    
    def recur(eles):
        for x in eles:
            if x and isinstance(x, list):
                recur(x)
            elif x != []:
                result.append(x)
        return result
    
    return recur(inp)


assert flatten(1,2,3) == [1,2,3]
assert flatten([1,2],[3,4,5],[6,[7],[[8]]]) == [1,2,3,4,5,6,7,8]
assert flatten(1,2,['9',[],[]],None) == [1,2,'9',None]

解题思路:利用递归。定义一个递归函数,循环判断函数的入参,如果参数是嵌套的列表类型,那么继续调用自己,直至所有的参数都是非嵌套的。其中,函数定义的flatten(*inp)中形参的*号的含义是函数可以接受不定长(个数不限)的实际参数。

参考题解

def flatten(*inp):
    
    def recur(eles):
        for x in eles:
            if isinstance(x, list):
                yield from recur(x)
            else:
                yield x
    
    return list(recur(inp))

assert flatten(1,2,3) == [1,2,3]
assert flatten([1,2],[3,4,5],[6,[7],[[8]]]) == [1,2,3,4,5,6,7,8]
assert flatten(1,2,['9',[],[]],None) == [1,2,'9',None]

解题思路:利用递归和生成器语法实现。

参考题解(极简代码)

def flatten(*inp):
    return [x for a in inp for x in (flatten(*a) if isinstance(a, list) else [a])]

assert flatten(1,2,3) == [1,2,3]
assert flatten([1,2],[3,4,5],[6,[7],[[8]]]) == [1,2,3,4,5,6,7,8]
assert flatten(1,2,['9',[],[]],None) == [1,2,'9',None]

解题思路:利用递归和列表推导式实现。语法简练,理解需要对其非常熟悉。功能相当于以下容易阅读的代码:

def flatten(*inp):
    
    result = []
    
    for a in inp:
        temp = None
        if isinstance(a, list):
            temp = flatten(*a)
        else:
            temp = [a]
        
        for x in temp:
            result.append(x)
        
    return result
关闭