【python】複数のリストの要素の全組み合わせを得る

Source Code Software Computerpython

itertoolsを使う方法がありますが、速度が遅かったため他の方法がないか探した時の記録です

itertoolsを使用する方法

import itertools

a = [i/100 for i in range(1000)]
b = [i/100 for i in range(100,2000)]

c = list(itertools.product(a,b))# 160ms

sklearnのcartesianを使用する方法

from sklearn.utils.extmath import cartesian

c = cartesian([a,b])# 80ms

cartesianの方が倍ほど高速

ただし、cartesian()は、一つ目のリストのデータ型を採用するようで、一個目がint、二個目がfloatだと、2個目のリストの値もint型に整形されてしまうのに注意が必要なようです。

scikit-learn/sklearn/utils/extmath.py at main · scikit-learn/scikit-learn
scikit-learn: machine learning in Python. Contribute to scikit-learn/scikit-learn development by creating an account on GitHub.

コメント

タイトルとURLをコピーしました