我正在嘗試使用 LC 在 Python 中展平一些混合陣列。我在弄清楚如何構建它時遇到了一些麻煩。
這是我想要展平的陣列
arr_1 = [1, [2, 3], 4, 5]
arr_2 = [1,[2,3],[[4,5]]]
我為 arr_1 嘗試了這種方法,但得到“TypeError:'int' object is not iterable”
print([item if type(items) is list else items for items in arr_1 for item in items])
所以我決定把它分成幾部分,看看它在哪里失敗了
def check(item):
return item;
print([check(item) if type(items) is list else check(items) for items in [1, [2, 3], 4, 5] for items in arr_2])
通過除錯器,我發現它在 2d 陣列中失敗了
for items in [1, [2, 3], 4, 5]
我不需要將 LC 放在一行中,但我只想知道如果可能的話,如何在單個嵌套 LC 中執行此操作。
uj5u.com熱心網友回復:
使用內部堆疊和iter的第二種形式來模擬while回圈:
def flatten(obj):
return [x
for stack in [[obj]]
for x, in iter(lambda: stack and [stack.pop()], [])
if isinstance(x, int)
or stack.extend(reversed(x))]
print(flatten([1, [2, 3], 4, 5]))
print(flatten([1, [2, 3], [[4, 5]]]))
print(flatten([1, [2, [], 3], [[4, 5]]]))
輸出(在線嘗試!):
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
稍微解釋一下,這里與普通代碼大致相同:
def flatten(obj):
result = []
stack = [obj]
while stack:
x = stack.pop()
if isinstance(x, int):
result.append(x)
else:
stack.extend(reversed(x))
return result
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456153.html
標籤:Python
下一篇:如何將顏色條添加到現有的軸手柄?
