How to generate a list from permutations of other lists in Mathematica
I am stuckwith a fairly simple problem: I need to construct a list with all permutations of values from two different lists in Mathematica.
Let say, a={1,2}
and b={4,5}
I would need the result
c={{1,开发者_如何学编程4},{1,5},{2,4},{2,5}}
Could anybody please give me an idea how to achieve this? Thanks a lot,
Philipp
Here is one way
In[2]:= Tuples[{{1, 2}, {4, 5}}]
Out[2]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}}
The built-in Tuples
function does precisely what you want:
In[1]:= a = {1, 2}; b = {4, 5};
In[2]:= c = Tuples[{a, b}]
Out[2]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}}
You can also accomplish this using Flatten
and the more general Outer
:
In[3]:= Flatten[Outer[List, a, b], 1]
Out[3]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}}
I mention this last fact because a lot of the time when I find myself using Tuples
, I'm doing so as an intermediate step before immediately Apply
ing a function to each of the generated sublists, and using Outer
can save me a step.
精彩评论