python 自定義函數將嵌套列表轉成一維列表

from collections.abc import Iterable


def flatten(item: Iterable):
    for x in item:
        # if isinstance(x, Iterable) and not isinstance(x, (str, bytes, dict)):
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x


print(list(flatten(['1', [2, '3'], [4, '5'], '6'])))
# ['1', 2, '3', 4, '5', '6']

print(list(flatten(['abc', [2, 'd'], [4, 'ef'], 'gh', {'test1': 'test1', 'test2': [1, 2]}])))
# ['abc', 2, 'd', 4, 'ef', 'gh', {'test1': 'test1', 'test2': [1, 2]}]

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章