我想展平可能包含其他列表的列表而不将字符串分开。例如:
In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )
Out[39]: ['c', 'a', 't', 'dog', 'bird']
我愿意
['cat', 'dog', 'bird']
最佳答案
解决办法:
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__') and not isinstance(x, str):
for y in flatten(x):
yield y
else:
yield x
Python 2.x 的旧版本:
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__'):
for y in flatten(x):
yield y
else:
yield x
(在 Python 2.x 中,字符串很方便地实际上没有 __iter__
属性,这与 Python 中几乎所有其他可迭代对象不同。但是请注意,它们在 Python 3 中具有,所以上面代码仅适用于 Python 2.x。)
关于python - 如何在不拆分字符串的情况下展平列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5286541/