将具有单个元素和列表的列表转换为平面列表

convert a list which has single elements and lists into a flat list

您将如何转换这样的列表:

["foo",["banana","apple"], "banana", ["peaches","grapes"]]

进入

["foo","banana","apple", "banana", "peaches",'grapes"]

我试过了:

flat_list = [item for sublist in regular_list for item in sublist]

使用嵌套 list 理解的一种方法可能是检查每个元素是否是 list,否则将其转换为列表类型:

regular_list = ["foo",["banana","apple"], "banana", ["peaches","grapes"]]


flat_list = [item for sublist in regular_list
             for item in (sublist if isinstance(sublist, list) else [sublist])]

print(flat_list)

结果:

['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
arr = ["foo", ["banana", "apple"], "banana", ["peaches", "grapes"]]

ans = []
for el in arr:
    ans.extend(el) if isinstance(el, list) else ans.append(el)
ans
# ['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']

如果嵌套的最大深度不是太大,可以使用递归来压平更深的嵌套:

def flatten(a):
    if not isinstance(a, list):
        yield a
        return
    for x in a:
        yield from flatten(x)

regular_list = ["foo",[[[["banana",[["apple"]]]]]], [[[["banana"]]]], ["peaches","grapes"]]
flat_list = list(flatten(regular_list))
print(flat_list)

输出

['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']