用途:
将类似:[[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
展开为:['a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3']
python2与报错解决
在python2中可以使用:
from compiler.ast import flatten
list_example = [[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
print(flatten(list_example))
python3
使用:
import collections.abc
def flatten(x):
result = []
for el in x:
if isinstance(x, collections.abc.Iterable) and not isinstance(el, str):
result.extend(flatten(el))
else:
result.append(el)
return result
if __name__ == '__main__':
list_example = [[['a', 'b'], 'c'], ['A', 'B', 'C'], '1', '2', '3']
print(flatten(list_example))