リストのグループからデカルト積 (可能な値のすべての組み合わせ) を取得するにはどうすればよいですか?
入力:
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
望ましい出力:
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]
リストのグループからデカルト積 (可能な値のすべての組み合わせ) を取得するにはどうすればよいですか?
入力:
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
望ましい出力:
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]
itertools.product
Python 2.6 から利用できます。
import itertools
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
for element in itertools.product(*somelists):
print(element)
これは、
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
print(element)
import itertools
>>> for i in itertools.product([1,2,3],['a','b'],[4,5]):
... print i
...
(1, 'a', 4)
(1, 'a', 5)
(1, 'b', 4)
(1, 'b', 5)
(2, 'a', 4)
(2, 'a', 5)
(2, 'b', 4)
(2, 'b', 5)
(3, 'a', 4)
(3, 'a', 5)
(3, 'b', 4)
(3, 'b', 5)
>>>
リスト内包表記を使用します:
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]
import itertools
result = list(itertools.product(*somelists))
これは、一時リストを保存しない再帰ジェネレーターです。
def product(ar_list):
if not ar_list:
yield ()
else:
for a in ar_list[0]:
for prod in product(ar_list[1:]):
yield (a,)+prod
print list(product([[1,2],[3,4],[5,6]]))
出力:
[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
Python 2.6以降では、「itertools.product」を使用できます。古いバージョンのPythonでは、少なくとも開始点として、ドキュメントから次の(ほぼ-ドキュメントを参照)同等のコードを使用できます。
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
両方の結果はイテレータであるため、さらに処理するためのリストが本当に必要な場合は、を使用してlist(result)
ください。
すでに述べたことに少し付け加えると、sympy を使用すると、文字列ではなく記号を使用できるため、数学的に有用になります。
import itertools
import sympy
x, y = sympy.symbols('x y')
somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]
for element in itertools.product(*somelist):
print element
sympyについて。
これは、
[(x, y) for x in range(10) for y in range(10)]
別の変数?問題ない:
[(x, y, z) for x in range(10) for y in range(10) for z in range(10)]
私はこれがうまくいくと信じています:
def cartesian_product(L):
if L:
return {(a,) + b for a in L[0]
for b in cartesian_product(L[1:])}
else:
return {()}
標準ライブラリで使用itertools.product
してデカルト積を取得できます。その他の優れた関連ユーティリティにitertools
はpermutations
、 、combinations
、およびが含まれますcombinations_with_replacement
。以下のスニペットの python codepen へのリンクを次に示します。
from itertools import product
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
result = list(product(*somelists))
print(result)