5
$\begingroup$

I have a list of list as follows:

{{5., 10., "Male"}, {6., 4., "Male"}, {5., 10., "Male"}, {5., 9., \
"Male"}, {5., 7., "Female"}, {6., 0., "Male"}, {5., 11., "Male"}, \
{5., 9., "Female"}, {5., 5., "Female"}}

The first two elements of the inner list specify the height of the subject in feets and inches. I would like to convert that to a List of list with just the height in Inches e.g.

{{70, "Male"}, {82, "Male"} .....}

What is the Map way of doing this?

$\endgroup$
0

1 Answer 1

8
$\begingroup$

Given

data = {{5., 10., "Male"}, {6., 4., "Male"}, {5., 10., 
    "Male"}, {5., 9., "Male"}, {5., 7., "Female"}, {6., 0., 
    "Male"}, {5., 11., "Male"}, {5., 9., "Female"}, {5., 5., 
    "Female"}};

You can use Map with

{12 #[[1]] + #[[2]], #[[3]]} & /@ data

(* {{70., "Male"}, {76., "Male"}, {70., "Male"}, {69., 
  "Male"}, {67., "Female"}, {72., "Male"}, {71., "Male"}, {69., 
  "Female"}, {65., "Female"}} *)

A slightly more concise version (suggested by @March) uses Apply

{12 #1 + #2, #3} & @@@ data

(* {{70., "Male"}, {76., "Male"}, {70., "Male"}, {69., 
  "Male"}, {67., "Female"}, {72., "Male"}, {71., "Male"}, {69., 
  "Female"}, {65., "Female"}} *)

And if you'd really like to abuse Mathematica, you can write

m = {{12, 0}, {1, 0}, {0, 1}};

Rationalize[data].m
(* {{70, "Male"}, {76, "Male"}, {70, "Male"}, {69, "Male"}, {67,
   "Female"}, {72, "Male"}, {71, "Male"}, {69, "Female"}, {65, 
  "Female"}} *)
$\endgroup$
2
  • 1
    $\begingroup$ Add the Apply version to your answer: {12 #1 + #2, #3} & @@@ list. $\endgroup$
    – march
    Commented Oct 1, 2016 at 20:29
  • $\begingroup$ If you list is really long, you can improve performance by using vector operations: Transpose@{12 #1 + #2, #3} & @@ Transpose@data, performance gain can be quite significant as shown here $\endgroup$
    – BlacKow
    Commented Oct 1, 2016 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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