4
$\begingroup$

How can I convert the this rule to a list:

input = {1 -> {71.52, 55.33}};

to:

output = {71.52, 55.33}
$\endgroup$
  • 2
    $\begingroup$ ReplaceAll: 1 /. input $\endgroup$ – corey979 Nov 4 '16 at 12:14
  • $\begingroup$ Thank you. So this is the same as ReplaceAll[1, input]. But what is the meaning of the expression 1? $\endgroup$ – lio Nov 4 '16 at 12:58
  • 3
    $\begingroup$ Use the answer by @Szabolcs. But in this simple case, you could use input[[1, 2]]. $\endgroup$ – Alan Nov 4 '16 at 13:13
9
$\begingroup$

For versions before 10.0, use Replace

Replace[1, input]
(* {71.52, 55.33} *)

I prefer to avoid ReplaceAll when Replace is appropriate. ReplaceAll works at all levels in an expression and is thus less predictable (or it makes a bigger mess if there's a bug in my code). Consider if you can potentially have multiple non-atomic keys in the rule list, some of which are sub-parts of others, e.g. {1 -> ..., a[1] -> ...}.

For 10.0 or later versions, use Lookup

Lookup[input, 1]
(* {71.52, 55.33} *)

Lookup is better for this use because it tells you if the key is missing from input.

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thank you very much for the explanation. $\endgroup$ – lio Nov 4 '16 at 13:02
1
$\begingroup$

it could be convenient to use Association for this, depending on what you are actually doing..

  Association[input][1]

{71.52, 55.33}

|improve this answer|||||
$\endgroup$
1
$\begingroup$

In general, you can convert list of rules into list of values, in the one of following four ways:

Last @@@ input
input[[All, 2]]
input /. Rule -> (#2 &)
Values@input
|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.