我怎样才能拼接列表而不分割string?

我想扁平化可能包含其他列表的列表, 而不要拆开string。 例如:

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__'): for y in flatten(x): yield y else: yield x 

(string方便地实际上并不具有__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 

orip回答略有修改,避免创build一个中间列表:

 import itertools items = ['cat',['dog','bird']] itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items) 

蛮力的方式是将string包装在自己的列表中,然后使用itertools.chain

 >>> l = ["cat", ["dog","bird"]] >>> l2 = [([x] if isinstance(x,str) else x) for x in l] >>> list(itertools.chain(*l2)) ['cat', 'dog', 'bird'] 
 def squash(L): if L==[]: return [] elif type(L[0]) == type(""): M = squash(L[1:]) M.insert(0, L[0]) return M elif type(L[0]) == type([]): M = squash(L[0]) M.append(squash(L[1:])) return M def flatten(L): return [i for i in squash(L) if i!= []] >> flatten(["cat", ["dog","bird"]]) ['cat', 'dog', 'bird'] 

希望这可以帮助