[英]Python extract multi-level nested lists
有這個清單
l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
我想獲得一個提取所有嵌套列表並返回的函數
l = [['a', 'b', 'c', 'd'],["d","d"],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]
像展平但保持每個嵌套列表的列表形成。 這是我最接近的一次,我覺得有一種方法可以在不使用額外結構來過濾重復項的情況下實現我的目標。 此外,順序在字符串和列表級別很重要。
def get_all_nested_list(l,returned_list):
nested_list = l
while isinstance(nested_list, list):
for elem in nested_list:
get_all_nested_list(elem,returned_list)
if isinstance(nested_list[0], str):
returned_list.append(nested_list)
nested_list = nested_list[0]
if __name__ == '__main__':
l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
l2 = []
get_all_nested_list(l,l2)
print(l2)
通過使用 itertools 或建議使用 yield 而不是將另一個列表作為參數傳遞的實際正確方法來執行上述操作的任何其他方法都非常受歡迎。
你可以試試遞歸函數
my_nested_list = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
def flatten(nested_list):
for item in nested_list:
if not isinstance(item[0],list):
yield item
else:
yield from flatten(item)
flat_list = [item for item in flatten(my_nested_list)]
print(flat_list)
你可以這樣做:
from itertools import chain
my_nested_list = [['a', 'b', 'c', 'd'],['e', ['r'], [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
def flatten(nested_list):
for item in nested_list:
if not isinstance(item,list):
yield item
elif list(chain(*item)) == item:
yield item
else:
yield from flatten(item)
flat_list = list(flatten(my_nested_list))
# [['a', 'b', 'c', 'd'], 'e', ['r'], ['d', 'd'], ['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.