この問題を手伝ってください: 数字とリストを含むリストがあります:
list = [1,2,[3,4,5],6,7,[8,9]]
私が取得したいのは、数字だけのリストです(親リストに含まれるリストをマージします):例:
new_list = [1,2,3,4,5,6,7,8,9]
再帰と の使用collections.Iterable
:
>>> from collections import Iterable
>>> def flat(lst):
... for parent in lst:
... if not isinstance(parent, Iterable):
... yield parent
... else:
... for child in flat(parent):
... yield child
...
>>> list(flat(t))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
独自のタイプにちなんでリストに名前を付けないことを忘れないでください:)。
私は個人的にこの方法を使用します:
これは、タプルとリストの両方を処理する recursive flatten の機能バージョンであり、位置引数の任意の組み合わせをスローできます。arg ごとに順番にシーケンス全体を生成するジェネレータを返します。
flatten = lambda *n: (e for a in n
for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))
使用法:
l1 = ['a', ['b', ('c', 'd')]]
l2 = [0, 1, (2, 3), [[4, 5, (6, 7, (8,), [9]), 10]], (11,)]
print list(flatten(l1, -2, -1, l2))
['a', 'b', 'c', 'd', -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
これは、python 3.x と python 2.x の両方で正常に動作します。
これは同じための正規表現ソリューションです..
import re
def Flatten(TheList):
a = str(TheList)
b,crap = re.subn(r'[\[,\]]', ' ', a)
c = b.split()
d = [int(x) for x in c]
return(d)