How can I flatten lists without splitting strings?
我想平展可能包含其他列表的列表,而不打断字符串。例如:
1 2 | In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) ) Out[39]: ['c', 'a', 't', 'dog', 'bird'] |
我想要
1 | ['cat', 'dog', 'bird'] |
号
1 2 3 4 5 6 7 | def flatten(foo): for x in foo: if hasattr(x, '__iter__'): for y in flatten(x): yield y else: yield x |
(conveniently没有。我有一个漂亮的
表格不X:Python的版本:
1 2 3 4 5 6 7 | 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 |
A你大学orip改性的答案,avoids中间产生的列表:
1 2 3 | import itertools items = ['cat',['dog','bird']] itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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'] |
希望这helps
一个蛮力的方式将是包在其自己的字符串列表,然后使用
1 2 3 4 | >>> l = ["cat", ["dog","bird"]] >>> l2 = [([x] if isinstance(x,str) else x) for x in l] >>> list(itertools.chain(*l2)) ['cat', 'dog', 'bird'] |