Python如何拉平(flatten)嵌套列表(nested list)
有时候会用到嵌套的列表(list),比如], ["abc", "def"]]
如果将嵌套的列表拉平(flatten)呢?变成:
方法有很多,目前了解到的各方面都比较好,也很pythonic的方法是:
def flatten(l):
for el in l:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
l = ], ["abc", "def"]]
l2 =
print l2
#
页:
[1]