2
$\begingroup$

If I have the following list:

list={{tau -> 32.8775, b -> 0.299216}, {tau -> 24.4891, 
  b -> 0.277134}, {tau -> 12.6688, b -> 0.356032}, {tau -> 4.84722, 
  b -> 0.30632}, {tau -> 0.134423, b -> 0.965791}, {tau -> 0.103983, 
  b -> 0.587649}, {tau -> 0.0610192, b -> 0.999985}};

How can I get one list with only the values of the different tau and another one with only the values of b. For example, for the first list I should get:

listtau={32.8775,24.4891,12.6688,4.84722,0.134423,0.103983,0.0610192}

Thank you

$\endgroup$
4
$\begingroup$
listtau = tau /. list
{32.8775, 24.4891, 12.6688, 4.84722, 0.134423, 0.103983, 0.0610192}
listb = b /. list
{0.299216, 0.277134, 0.356032, 0.30632, 0.965791, 0.587649, 0.999985}

Or, both lists in a single step:

{listtau, listb} = ReplaceAll[list] /@ {tau, b}
{{32.8775, 24.4891, 12.6688, 4.84722, 0.134423, 0.103983,  0.0610192}, 
{0.299216, 0.277134, 0.356032, 0.30632, 0.965791, 0.587649, 0.999985}}

You can also use

Transpose[{tau, b} /. list]

Values[FilterRules[list, #]] & /@ {tau, b} 

GroupBy[Join @@ list, First -> Last] /@ {tau, b}

Lookup[{tau, b}] @ Merge[list, Identity]

Merge[list, Identity] /@ {tau, b}

Values @ Merge[Identity] @ list

Transpose @ Values @ list

Transpose[list /. Rule -> Last]

to get the same result.

Note: The last three methods assume that the ordering of the rules tau -> .. and b -> .. is the same in all sublists.

$\endgroup$
  • 1
    $\begingroup$ I'd say that Lookup[list, tau] and Lookup[list, b] are the idiomatic ways to do this. $\endgroup$ – Sjoerd Smit Dec 21 '20 at 7:52
2
$\begingroup$
First /@ Values[list]
Last /@ Values[list]
$\endgroup$
  • $\begingroup$ Values /@ list // Thread $\endgroup$ – cvgmt Dec 21 '20 at 0:55
2
$\begingroup$
{listtau, listb} = Transpose@list[[;; , ;; , 2]]
$\endgroup$
2
$\begingroup$

Simplicity of the approach tau /. list and b /. list makes it quite natural to exploit. Nevertheless one can take into account another approach which can appear to be more efficient for long lists:

listtau = Last @@@ First @ Transpose @ list
listb = Last @@@ Last @ Transpose @ list
{32.8775, 24.4891, 12.6688, 4.84722, 0.134423, 0.103983, 0.0610192}
{0.299216, 0.277134, 0.356032, 0.30632, 0.965791, 0.587649, 0.999985}

It might be reasonable to consider also:

list[[All, 1, 2]]
list[[All, 2, 2]]
$\endgroup$
0
$\begingroup$

Here are a couple of more ways to extract tau and b from list

Method 1

assoc = Association[#] & /@ list;
listTau = #[tau] & /@ assoc
listB = #[b] & /@ assoc

Method 2

listTau = Values[First[#]] & /@ list
listB = Values[Last[#]] & /@ list
$\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.