Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Apply a function to parts of a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110369] Re: Apply a function to parts of a list
  • From: Alexei Boulbitch <alexei.boulbitch at iee.lu>
  • Date: Tue, 15 Jun 2010 02:31:11 -0400 (EDT)

    *   /From/: Leonid Shifrin <lshifr at gmail.com>
    * /Date/: Sun, 13 Jun 2010 04:10:46 -0400 (EDT)

------------------------------------------------------------------------

Hi, Rui, 
this is another possibility:

lst = {{a, 5}, {b, 6}, {c, 7}};

(* This is the function ...*)
g[{x_, y_}] := {x, y/2} // N;
(* ...to be mapped on the list *)
Map[g, lst]

{{a, 2.5}, {b, 3.}, {c, 3.5}}

Have fun, Alexei


Hi Rui,

The methods you listed are perfectly fine IMO. You may want to consider a
rule-based solution as well:

In[1]:= Replace[{{a, 5}, {b, 6}, {c, 7}}, {a_, b_} :> {a, b/2}, 1]

Out[1]= {{a, 5/2}, {b, 3}, {c, 7/2}}

Using ReplaceAll may fail in some cases since the rule based on generic
patterns may sometimes be  applied one level higher than desired:

In[3]:= {{a, 5}, {b, 6}} /. {a_, b_} :> {a, b/2}

Out[3]= {{a, 5}, {b/2, 3}}


Regards,
Leonid


On Sat, Jun 12, 2010 at 2:32 AM, Rui <rui.rojo at gmail.com> wrote:

> I have always done very ugly code when trying to do something
> seemingly simple and basic such as applying a function to subparts of a
> list.
> Simple example, I want to divide by 2 all the second elements of a
> list
> {{a, 5}, {b, 6}, ...}   -->  {{a, 5/2}, ...}
>
> My ideas:
> Transpose -> MapAt/Map -> Transpose
> Build the sublist with Part and then rebuild it
> Use Map and a function like #[[All, 2]] and then rebuild it.
>
> I don't like any solution. I wanted to know if there's anything simple
> that I'm overseing
>
> Thanks guys
>
>

-- 
Alexei Boulbitch, Dr. habil.
Senior Scientist
Material Development

IEE S.A.
ZAE Weiergewan
11, rue Edmond Reuter
L-5326 CONTERN
Luxembourg

Tel: +352 2454 2566
Fax: +352 2454 3566
Mobile: +49 (0) 151 52 40 66 44

e-mail: alexei.boulbitch at iee.lu

www.iee.lu

--

This e-mail may contain trade secrets or privileged, undisclosed or
otherwise confidential information. If you are not the intended
recipient and have received this e-mail in error, you are hereby
notified that any review, copying or distribution of it is strictly
prohibited. Please inform us immediately and destroy the original
transmittal from your system. Thank you for your co-operation.



  • Prev by Date: Re: Dynamic window popup question
  • Next by Date: Washington DC Area Mathematica Special Interest Group
  • Previous by thread: Re: Apply a function to parts of a list
  • Next by thread: Re: Apply a function to parts of a list