[英]Function with while loop no breaking
這是代碼:
def unnestList(l):
result=[]
for elem in l:
while True:
if not isinstance(elem,list):
break
else:
for e in elem:
if isinstance(e,list):
elem = e[:]
continue
else:
break
result.append(elem)
return result
所以我試圖取消嵌套(對不起,如果它不是正確的詞)不規則列表的列表。 樣本輸入:
[['A','B'],[['A']]]
[[['A', 'B', 'C']], [[[['A', 'D', 'E', 'B', 'C']]]]]
預期 output:
[['A','B'],['A']]
[['A', 'B', 'C'],['A', 'D', 'E', 'B', 'C']]
while True
循環在所有情況下都沒有終止條件。 完全刪除它(如 Kfir Ram 的回答)似乎可以解決您的示例輸入的問題,但不能處理更深的嵌套。
遞歸解決方案會更容易遵循 IMO:
>>> def unnest_list(obj):
... if not isinstance(obj, list):
... return obj
... if len(obj) == 1 and isinstance(obj[0], list):
... return unnest_list(obj[0])
... return [unnest_list(i) for i in obj]
...
>>> unnest_list([[[[[[['A']]]]]], [[[[[['B']]]]]]])
[['A'], ['B']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.