是的,我知道這個主題之前已經討論過(這裡,這裡,這裡,這裡),但據我所知,除了一個之外,所有解決方案都在這樣的列表中失敗:
L = [[[1, 2 , 3], [4, 5]], 6]
期望的輸出是
[1, 2, 3, 4, 5, 6]
或者甚至更好,一個迭代器。我看到的唯一適用於任意嵌套的解決方案是 in this question:
def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result flatten(L)
這是最好的模型嗎?我忽略了什麼嗎?有什麼問題嗎?