Warm tip: This article is reproduced from stackoverflow.com, please click
permutation python combinations

All possible combinations of elements of three vectors in Python

发布于 2020-03-31 23:00:38

I have three lists, each containing lets say 2 elements. How can I obtain a (8x3) array which contains all the possible combinations (with replacement) of the elements in the three lists?

Example:

vec1 = [4, 6]
vec2 = [2, 4]
vec3 = [1, 5]

output = [[4, 2, 1], [4, 2, 5], [4, 4, 1], [4, 4, 5], [6, 2, 1], [6, 4, 5], [6, 2, 5], [6, 4, 1]]

This is my code (simplified):

import scipy.stats as st
percentiles = [0.01, 0.99]
draws1 = st.norm.ppf(percentiles, 0, 1)
draws2 = st.norm.ppf(percentiles, 0, 1)
draws3 = st.norm.ppf(percentiles, 0, 1)
Questioner
matthew
Viewed
45
lemac 2020-01-31 20:12

You could use numpy.meshgrid() like so:

np.array(np.meshgrid([4, 6], [2, 4], [1, 5])).T.reshape(-1,3)

Which results in:

 array([[4, 2, 1],
       [4, 4, 1],
       [6, 2, 1],
       [6, 4, 1],
       [4, 2, 5],
       [4, 4, 5],
       [6, 2, 5],
       [6, 4, 5]])