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]}]

浙公网安备 33010602011771号