LoginSignup
2
1

More than 5 years have passed since last update.

特定配列内の長さの不定な配列同士の直積を得る。

Posted at

上手いタイトルが付けられなかったのですが、やりたいことは単純です。

やりたいこと

長さが違う長さが違う配列の配列の直積を得たい!

A = [[1,2],[3,4]]
f(A)

↑これの出力がこれ↓

(1, 3)
(1, 4)
(2, 3)
(2, 4)
B = [[1],[2,3],[4,5,6]]
f(B)

↑これの出力がこれ↓

(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)

unpack!

*をつけると配列とか辞書をほぐせるらしい。

A = [1,2]
print(*A) #1 2 

つまり!こんなふうに書けばいい↓

import itertools

def f(X):
    for x in itertools.product(*X):
        print(x)

A = [[1,2],[3,4]]
B = [[1],[2,3],[4,5,6]]

f(A)
f(B)

これでいい!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1