どのようにフラットリストの一覧リスト
-
11-09-2019 - |
質問
のかという問題があるように思うがショートカットを簡単なリストの一覧リスト。
私はそれを実行できる for
ループが、もしかしたら、あとなるヨーロッパをテーマにした"一つのライナー?てみましたので 削減, んとエラーとなります。
コード
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
エラーメッセージ
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
解決
リストのl
のリストを考えると、
flat_list = [item for sublist in l for item in sublist]
を意味します:
flat_list = []
for sublist in l:
for item in sublist:
flat_list.append(item)
これまでに掲載のショートカットよりも高速です。 (l
が平坦化するリストです。)
ここでは、対応する機能です。
flatten = lambda l: [item for sublist in l for item in sublist]
証拠として、あなたは、標準ライブラリにtimeit
モジュールを使用することができます:
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop
説明:Lのサブリストがある場合+
、ある(sum
で暗黙の使用を含む)必要のO(L**2)
に基づいてショートカット - 中間結果のリストがそれぞれに、長くなっ保つように、新しい中間結果リストオブジェクトが取得するステップ割り当てられ、前の中間結果のすべての項目がコピーされなければならない(並びに最後に追加いくつかの新しいもの)。 ;最初のI項目回、第二I項目のL-2倍前後にL-1をコピーし、というようにされていますので、簡単にするために一般性を実際の損失なしに、あなたは私の項目それぞれのLのサブリストが持っていると言いますコピーの総数は除外さL 1〜xのxのI倍の和である、すなわち、I * (L**2)/2
。
リストの内包は、ちょうどまた、一度だけ(結果リストに居住の元の場所から)各項目の上に一度、1つのリストを作成し、コピーします。
他のヒント
あなたが使用することができます itertools.chain()
するます:
>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))
または、パイソン> = 2.6で、使用 itertools.chain.from_iterable()
リストを開梱必要としない。
>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))
このアプローチは[item for sublist in l for item in sublist]
よりも間違いなく、より読みやすいですし、あまりにも速いように見えます:
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
10000 loops, best of 3: 24.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 45.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 488 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 522 usec per loop
[me@home]$ python --version
Python 2.7.3
の作者から注:これは非効率的です。しかし、楽しい、モノイドのは素晴らしいですので。これは、生産Pythonコードに適切ではありません。
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
これは単に(与えられていない場合、0
が代わりに使用され、この場合はあなたにエラーを与える)和の初期値として、二番目の引数を処理する、最初の引数に渡されたイテラブルの要素を合計する。
あなたがネストされたリストを加算しているので、あなたが実際に[1,3]+[2,4]
に等しいsum([[1,3],[2,4]],[])
の結果として[1,3,2,4]
を取得します。
唯一のリストのリストで動作することに注意してください。リストのリストのリストでは、あなたは別のソリューションが必要になります。
私は perfplot に(私のペットプロジェクト、timeit
周りの基本的ラッパー)と最も提案のソリューションをテストしました、見つかった
functools.reduce(operator.iconcat, a, [])
最速の解決策になります。 (operator.iadd
が均等に高速である。)
プロットを再現するコード:
import functools
import itertools
import numpy
import operator
import perfplot
def forfor(a):
return [item for sublist in a for item in sublist]
def sum_brackets(a):
return sum(a, [])
def functools_reduce(a):
return functools.reduce(operator.concat, a)
def functools_reduce_iconcat(a):
return functools.reduce(operator.iconcat, a, [])
def itertools_chain(a):
return list(itertools.chain.from_iterable(a))
def numpy_flat(a):
return list(numpy.array(a).flat)
def numpy_concatenate(a):
return list(numpy.concatenate(a))
perfplot.show(
setup=lambda n: [list(range(10))] * n,
kernels=[
forfor, sum_brackets, functools_reduce, functools_reduce_iconcat,
itertools_chain, numpy_flat, numpy_concatenate
],
n_range=[2**k for k in range(16)],
logx=True,
logy=True,
xlabel='num lists'
)
from functools import reduce #python 3
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(lambda x,y: x+y,l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
あなたの例でextend()
方法ではなく(x
が期待)の有用な値を返すreduce()
を変更します。
reduce
バージョンを行うにはより高速な方法は次のようになります。
>>> import operator
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.concat, l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
ここでは一般的なアプローチに適用される 番号, 文字列, 入れ子 リスト 混合 コンテナ
コード
#from typing import Iterable
from collections import Iterable # < py38
def flatten(items):
"""Yield items from any nested iterable; see Reference."""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatten(x):
yield sub_x
else:
yield x
注記:
- Python3,
yield from flatten(x)
交換可能でfor sub_x in flatten(x): yield sub_x
- Pythonでは38, 抽象基底クラス は 移転 から
collection.abc
のtyping
モジュールです。
デモ
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(flatten(lst)) # nested lists
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
mixed = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"] # numbers, strs, nested & mixed
list(flatten(mixed))
# [1, 2, 3, 4, 5, 6, 7, 8, '9']
参考
- このソリューションが変更されたからレシピ Beazley,D.B.ー-ジョーンズ。レシピ4.14、Python Cookbook3rd Ed., オライリー-メディア株式会社セバストポルCA:2013.
- たり前の でポスト, あの。
したい場合はカーブを平坦化データ構造がいかに深部で入れ子を使用できる iteration_utilities.deepflatten
1
>>> from iteration_utilities import deepflatten
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(deepflatten(l, depth=1))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]
>>> list(deepflatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
で発生器ばなければなりませんでしキャストの結果を list
または明示的に繰り返し処理を実行します。
平らに一つだけのレベルがそれぞれの項目は自身のlistも利用できます iteration_utilities.flatten
自分には薄いラッパ itertools.chain.from_iterable
:
>>> from iteration_utilities import flatten
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(flatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
るだけで追加のタイミングに基づくニSchlömer答えるなどの機能をこれで解答):
でログ-logプロット対応の巨大な範囲の値の張る.定性的推論:下がります。
その結果の場合のlistを含んだ内iterablesし sum
が、しかし長iterablesのみ itertools.chain.from_iterable
, iteration_utilities.deepflatten
またはメソッドは、入れ子の内包して合理的な性能 itertools.chain.from_iterable
の最速していニSchlömer).
from itertools import chain
from functools import reduce
from collections import Iterable # or from collections.abc import Iterable
import operator
from iteration_utilities import deepflatten
def nested_list_comprehension(lsts):
return [item for sublist in lsts for item in sublist]
def itertools_chain_from_iterable(lsts):
return list(chain.from_iterable(lsts))
def pythons_sum(lsts):
return sum(lsts, [])
def reduce_add(lsts):
return reduce(lambda x, y: x + y, lsts)
def pylangs_flatten(lsts):
return list(flatten(lsts))
def flatten(items):
"""Yield items from any nested iterable; see REF."""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
def reduce_concat(lsts):
return reduce(operator.concat, lsts)
def iteration_utilities_deepflatten(lsts):
return list(deepflatten(lsts, depth=1))
from simple_benchmark import benchmark
b = benchmark(
[nested_list_comprehension, itertools_chain_from_iterable, pythons_sum, reduce_add,
pylangs_flatten, reduce_concat, iteration_utilities_deepflatten],
arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)},
argument_name='number of inner lists'
)
b.plot()
1免責事項:私の著書であること図書館
の私は私の文を取り戻します。合計は勝者ではありません。それは高速ですが、リストが小さい場合。しかし、パフォーマンスは大きなリストを大幅に低下します。の
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10000'
).timeit(100)
2.0440959930419922
和バージョンはまだ1分以上実行されていて、それがまだ処理を行っていません!
メディアのリストを示します。
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
20.126545906066895
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
22.242258071899414
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
16.449732065200806
小さなリストとはtimeitを使用して:数= 1000000
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
2.4598159790039062
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.5289170742034912
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.0598428249359131
operator.add
との混乱があるようです!あなたが一緒に二つのリストを追加すると、そのための正しい用語はconcat
で、追加しません。 operator.concat
は、使用するために必要なものです。
、それはこのように簡単です::
>>> from functools import reduce
>>> list2d = ((1, 2, 3), (4, 5, 6), (7,), (8, 9))
>>> reduce(operator.concat, list2d)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
あなたはタプルを供給するときに、あなたはタプルを取り戻す、シーケンスタイプの点を減らすご覧ください。リストにしてみましょう::
>>> list2d = [[1, 2, 3],[4, 5, 6], [7], [8, 9]]
>>> reduce(operator.concat, list2d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
なるほど、あなたはリストを取り戻すます。
どのようにパフォーマンスについて::
>>> list2d = [[1, 2, 3],[4, 5, 6], [7], [8, 9]]
>>> %timeit list(itertools.chain.from_iterable(list2d))
1000000 loops, best of 3: 1.36 µs per loop
from_iterable
はかなり速いです!しかし、それはconcat
を減らすために何の比較ません。
>>> list2d = ((1, 2, 3),(4, 5, 6), (7,), (8, 9))
>>> %timeit reduce(operator.concat, list2d)
1000000 loops, best of 3: 492 ns per loop
なぜあなたは延長使っていますか?
reduce(lambda x, y: x+y, l)
これは正常に動作する必要があります。
検討を設置 more_itertools
パッケージです。
> pip install more_itertools
で船の実装 flatten
(源, から、 itertoolsレシピ):
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
としてのバージョン2.4できるカーブを平坦化複雑化し、入れ子iterablesと more_itertools.collapse
(源, しabarnet).
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9] # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
あなたの機能は動作しませんでした理由:延長は、インプレース配列を拡張し、それを返しません。あなたはまだいくつかのトリックを使用して、ラムダからのxを返すことができます:
reduce(lambda x,y: x.extend(y) or x, l)
注:拡張がリストに+よりも効率的です。
。な管理ソリューションを提ホイールをご利用の場合 Django:
>>> from django.contrib.admin.utils import flatten
>>> l = [[1,2,3], [4,5], [6]]
>>> flatten(l)
>>> [1, 2, 3, 4, 5, 6]
...パンダ:
>>> from pandas.core.common import flatten
>>> list(flatten(l))
...Itertools:
>>> import itertools
>>> flatten = itertools.chain.from_iterable
>>> list(flatten(l))
...Matplotlib
>>> from matplotlib.cbook import flatten
>>> list(flatten(l))
...Unipath:
>>> from unipath.path import flatten
>>> list(flatten(l))
...Setuptools:
>>> from setuptools.namespaces import flatten
>>> list(flatten(l))
def flatten(l, a):
for i in l:
if isinstance(i, list):
flatten(i, a)
else:
a.append(i)
return a
print(flatten([[[1, [1,1, [3, [4,5,]]]], 2, 3], [4, 5],6], []))
# [1, 1, 1, 3, 4, 5, 2, 3, 4, 5, 6]
上記アニルの機能の悪い特徴は、常に手動で空のリスト[]
する第二引数を指定することを必要とすることです。これは、代わりにデフォルトにする必要があります。 Pythonオブジェクトの作業方法のため、これらはないの引数に、関数内で設定する必要があります。
ここで働く機能です。
def list_flatten(l, a=None):
#check a
if a is None:
#initialize with empty list
a = []
for i in l:
if isinstance(i, list):
list_flatten(i, a)
else:
a.append(i)
return a
テスト
In [2]: lst = [1, 2, [3], [[4]],[5,[6]]]
In [3]: lst
Out[3]: [1, 2, [3], [[4]], [5, [6]]]
In [11]: list_flatten(lst)
Out[11]: [1, 2, 3, 4, 5, 6]
も、彼らは巣場合matplotlib.cbook.flatten()
は、例えば、より深くネストされたリストのために動作します。
import matplotlib
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(list(matplotlib.cbook.flatten(l)))
l2 = [[1, 2, 3], [4, 5, 6], [7], [8, [9, 10, [11, 12, [13]]]]]
print list(matplotlib.cbook.flatten(l2))
結果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
このは、アンダースコア._よりも18倍高速であるフラット化:ます。
Average time over 1000 trials of matplotlib.cbook.flatten: 2.55e-05 sec
Average time over 1000 trials of underscore._.flatten: 4.63e-04 sec
(time for underscore._)/(time for matplotlib.cbook) = 18.1233394636
受け入れ答えは私のために動作しませんでした。ここでは私のために仕事をした別のアプローチがある。
l = ['aaa', 'bb', 'cccccc', ['xx', 'yyyyyyy']]
のないの仕事をした受け入れ答え
flat_list = [item for sublist in l for item in sublist]
print(flat_list)
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'xx', 'yyyyyyy']
<全角> 新提案された解決策は私のためのの仕事でした:
flat_list = []
_ = [flat_list.extend(item) if isinstance(item, list) else flat_list.append(item) for item in l if item]
print(flat_list)
['aaa', 'bb', 'cccccc', 'xx', 'yyyyyyy']
flat_list = [item for sublist in l for item in sublist]
print(flat_list)
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'xx', 'yyyyyyy']
flat_list = []
_ = [flat_list.extend(item) if isinstance(item, list) else flat_list.append(item) for item in l if item]
print(flat_list)
['aaa', 'bb', 'cccccc', 'xx', 'yyyyyyy']
再帰バージョン
x = [1,2,[3,4],[5,[6,[7]]],8,9,[10]]
def flatten_list(k):
result = list()
for i in k:
if isinstance(i,list):
#The isinstance() function checks if the object (first argument) is an
#instance or subclass of classinfo class (second argument)
result.extend(flatten_list(i)) #Recursive call
else:
result.append(i)
return result
flatten_list(x)
#result = [1,2,3,4,5,6,7,8,9,10]
に続いて私には、最も簡単なように見えるます:
>>> import numpy as np
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> print (np.concatenate(l))
[1 2 3 4 5 6 7 8 9]
1つはまたnumpyののフラット:
import numpy as np
list(np.array(l).flat)
編集2016年11月2日:サブリストは、同一の寸法を有している場合にのみ動作します。
。あなたはnumpyの使用することができます。
flat_list = list(np.concatenate(list_of_list))
の簡易コード underscore.py
のパッケージファン
from underscore import _
_.flatten([[1, 2, 3], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
これは、すべてのフラット化の問題(なしリスト項目や複雑な入れ子に)
を解決しますfrom underscore import _
# 1 is none list item
# [2, [3]] is complex nesting
_.flatten([1, [2, [3]], [4, 5, 6], [7], [8, 9]])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
あなたがインストールすることができます underscore.py
のピップと
pip install underscore.py
def flatten(alist):
if alist == []:
return []
elif type(alist) is not list:
return [alist]
else:
return flatten(alist[0]) + flatten(alist[1:])
flat_list = []
for i in list_of_list:
flat_list+=i
それだけでリストのすべての方法を拡張すると、このコードは、正常に動作します。それは非常に似ていますが、唯一のループのための1つを持っているが。だから、それはループの2を加えるより少ない複雑さを持っています。
あなたはきれいな外観のための速度のわずかな量をあきらめて喜んでいる場合、あなたはnumpy.concatenate().tolist()
やnumpy.concatenate().ravel().tolist()
を使用することができます:
import numpy
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] * 99
%timeit numpy.concatenate(l).ravel().tolist()
1000 loops, best of 3: 313 µs per loop
%timeit numpy.concatenate(l).tolist()
1000 loops, best of 3: 312 µs per loop
%timeit [item for sublist in l for item in sublist]
1000 loops, best of 3: 31.5 µs per loop
あなたは numpy.concatenateドキュメントで、よりここに見つけることができますと numpy.ravelする
(とにかく大規模なリストのために)私が見つけた最速の解決策ます:
import numpy as np
#turn list into an array and flatten()
np.array(l).flatten()
完了!あなたはもちろん、リストを実行することによって、リストに戻ってそれを回すことができる(L)
これは、最も効率的な方法ではないかもしれないが、私はワンライナー(実際には2ライナー)を置くことを考えました。どちらのバージョンは、任意の階層ネストされたリスト上で動作し、言語機能(Python3.5)と再帰を利用します。
def make_list_flat (l):
flist = []
flist.extend ([l]) if (type (l) is not list) else [flist.extend (make_list_flat (e)) for e in l]
return flist
a = [[1, 2], [[[[3, 4, 5], 6]]], 7, [8, [9, [10, 11], 12, [13, 14, [15, [[16, 17], 18]]]]]]
flist = make_list_flat(a)
print (flist)
が出力される
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
これは、深さ優先の方法で動作します。それは、非リスト要素を見つけ、ローカル変数flist
を拡張して、親に戻ってそれをロールするまで再帰がダウンします。 flist
が返されるたびに、それはリスト内包で親のflist
に拡張されます。そのため、ルートで、フラットなリストが返されます。
上記1には、いくつかのローカルリストを作成し、親のリストを拡張するために使用され、それらを返します。私はこのために回避する方法は、以下のように、gloabl flist
を作成することができると考えています。
a = [[1, 2], [[[[3, 4, 5], 6]]], 7, [8, [9, [10, 11], 12, [13, 14, [15, [[16, 17], 18]]]]]]
flist = []
def make_list_flat (l):
flist.extend ([l]) if (type (l) is not list) else [make_list_flat (e) for e in l]
make_list_flat(a)
print (flist)
出力は再びです。
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
私は、この時点での効率について確認していないもののます。
注意:以下に適用されPython3.3+で yield_from
. six
も第三者パッケージにも安定しています。交互にあらか sys.version
.
の場合 obj = [[1, 2,], [3, 4], [5, 6]]
, 全てのソリューションここでは、リストの理解と itertools.chain.from_iterable
.
しかし、このことを考え少し複雑なものの場合:
>>> obj = [[1, 2, 3], [4, 5], 6, 'abc', [7], [8, [9, 10]]]
問題点はいくつもありがここに:
- 一つの要素
6
, をかけることができるスカラー;でないlistので、上記のルートに失敗します。 - 一つの要素
'abc'
, は 技術のlist(全str
s。しかし、読みの間を、少なく、扱いたいのでどなど--いて単一の要素です。 - 最後の要素
[8, [9, 10]]
それ自体が入れ子のlist.基本リストの理解とchain.from_iterable
みエキスを"1レベル。"
できる治療としており
>>> from collections import Iterable
>>> from six import string_types
>>> def flatten(obj):
... for i in obj:
... if isinstance(i, Iterable) and not isinstance(i, string_types):
... yield from flatten(i)
... else:
... yield i
>>> list(flatten(obj))
[1, 2, 3, 4, 5, 6, 'abc', 7, 8, 9, 10]
ここでは、チェックのサブ要素(1)のlistと Iterable
, は、ABCから itertools
, も行っている(2)の要素 ない "文字列。"
ヘテロと整数の均質なリストのために働く別の珍しいアプローチます:
from typing import List
def flatten(l: list) -> List[int]:
"""Flatten an arbitrary deep nested list of lists of integers.
Examples:
>>> flatten([1, 2, [1, [10]]])
[1, 2, 1, 10]
Args:
l: Union[l, Union[int, List[int]]
Returns:
Flatted list of integer
"""
return [int(i.strip('[ ]')) for i in str(l).split(',')]
簡単に再帰的方法を用い reduce
から functools
の add
オペレーターモニタリングシステム:
>>> from functools import reduce
>>> from operator import add
>>> flatten = lambda lst: [lst] if type(lst) is int else reduce(add, [flatten(ele) for ele in lst])
>>> flatten(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
の機能 flatten
取り lst
パラメータとしてでループの全ての要素について lst
まで到達整数(変更することも出来ます int
へ float
, str
, など。その他のデータタイプ)を返却値の型に"byte[]"を指定一番外側の再帰.
再帰な方法のように for
ループmonadsで 一般解による限定は受けない、リストの深さ.例えば、リストの深さ5で平坦化されたと同じように l
:
>>> l2 = [[3, [1, 2], [[[6], 5], 4, 0], 7, [[8]], [9, 10]]]
>>> flatten(l2)
[3, 1, 2, 6, 5, 4, 0, 7, 8, 9, 10]