如何在不分割字符串的情况下拼合列表?
发布于 2021-01-29 15:17:18
我想拼合可能包含其他列表的列表, 但不要 弄乱字符串。例如:
In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )
Out[39]: ['c', 'a', 't', 'dog', 'bird']
我想
['cat', 'dog', 'bird']
关注者
0
被浏览
139
1 个回答
-
def flatten(foo): for x in foo: if hasattr(x, '__iter__'): for y in flatten(x): yield y else: yield x
(
__iter__
与Python中几乎所有其他可迭代对象不同,字符串实际上实际上并不具有属性。但是请注意,这在Python
3中有所变化,因此上述代码仅在Python 2.x中有效。)适用于Python 3.x的版本:
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