Re: Apply a function to parts of a list
- To: mathgroup at smc.vnet.net
- Subject: [mg110331] Re: Apply a function to parts of a list
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Sun, 13 Jun 2010 04:12:46 -0400 (EDT)
data = Thread[Array[#, 3] & /@ {x, y}]
{{x[1], y[1]}, {x[2], y[2]},
{x[3], y[3]}}
data /. {a_, b_} -> {a, b/2}
{{x[1], y[1]/2}, {x[2], y[2]/2},
{x[3], y[3]/2}}
{1, 1/2} # & /@ data
{{x[1], y[1]/2}, {x[2], y[2]/2},
{x[3], y[3]/2}}
{#[[1]], #[[2]]/2} & /@ data
{{x[1], y[1]/2}, {x[2], y[2]/2},
{x[3], y[3]/2}}
Bob Hanlon
---- 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