三国纷争
你可以递归地做到这一点:def flatten(l, level=None): if level == 0: return l flattened = [] for item in l: if isinstance(item, list): flattened.extend(flatten(item, level-1 if level is not None else None)) else: flattened.append(item) return flattenedls2 = [1,[2,3],[4,[5,6]]]print(flatten(ls2, level=1))# [1, 2, 3, 4, [5, 6]]print(flatten(ls2, level=2))# [1, 2, 3, 4, 5, 6]print(flatten(ls2))# [1, 2, 3, 4, 5, 6]
largeQ
一种方法ls2 = [1,[2,3],[4,[5,6]]]def make_list_of_list(a): return [[i]if not isinstance(i, list) else i for i in a]def flatten(l): return [item for sublist in make_list_of_list(l) for item in sublist]flatten(ls2) will result in [1, 2, 3, 4, [5, 6]]flatten(flatten(ls2)) will result in [1, 2, 3, 4, 5, 6]