Say I have a list called A and I want to divide it into two separate list B and C by looping through A and picking out one element to add to B and one to add to A throughout the length of A.
Don't use For
. Really. Never.
There are much more elegant ways, for example
a = Range[20];
{b, c} = Transpose[Partition[a, 2]]
{{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}, {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}
or (should be the fastest; look up Span
to understand it)
b = a[[1;; ;;2]]
c = a[[2;; ;;2]]
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
or
{b, c} = GatherBy[a, OddQ]
{{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}, {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}
or
b = Select[a, OddQ]
c = Select[a, EvenQ]
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
In the last two examples, you may replace OddQ
and EvenQ
by any other function that returns True
or False
in order to realize other decision rules.
-
$\begingroup$ Only the middle approach is robust. +1 for it. $\endgroup$ – Bob Hanlon Nov 2 '18 at 0:25
As it turns out, there is a special function for taking every other element called DownSample:
list = Range[20];
a = Downsample[list, 2]
b = Downsample[list, 2, 2]
a has all the odd values, b has all the evens.
list = Range@20;
here are alternatives
TakeDrop[list, {1, -1, 2}]
{{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}, {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}
and here is random separation
{d = RandomSample[s, Length@list/2], Complement[list, d]}
{{4, 12, 5, 19, 3, 11, 17, 16, 6, 10}, {1, 2, 7, 8, 9, 13, 14, 15, 18, 20}}
Select
elements, whichCases
define how toSplit
the list, and most importantly: the code of what you have tried so far. $\endgroup$ – rhermans Nov 1 '18 at 18:25For
loop, but probably something in the lines ofSelect
,Cases
orSplit
. Your question may be put on-hold because its unanswerable for lack of details. We can't help unless you edit your question to improve it and make it specific, with all the details one would need to reproduce your problem exactly. Please don't be discouraged by that cleaning-up policy. Your questions are and will be most welcomed. Learn about good questions here. $\endgroup$ – rhermans Nov 1 '18 at 18:28For
loop is a very awkward and inefficient way to accomplish what you seek. By what criterion do you place elements into $B$ or $C$? Simple alternates? $\endgroup$ – David G. Stork Nov 1 '18 at 18:30