MathGroup Archive 2005

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

Search the Archive

Re: enumerating list items


>-----Original Message-----
>From: Søren Merser [mailto:merser at image.dk] 
To: mathgroup at smc.vnet.net
>Sent: Tuesday, April 12, 2005 11:27 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg55982] [mg55976] enumerating list items
>
>hi
>
>is there a way to make each item in the list 'assignable', 
>i.e. i want to 
>enumerate the items like id=1, gender=2 etc.
>
>a={"id", "gender", "status", "odag"}
>
>b=Range@Length@a
>
>a=b
>
>regards soren
>
>
>

You have to convert the strings to symbols, before you can assign to them. This works, provided the symbols already don't exist with values:

In[1]:= a={"id","gender","status","odag"};

In[2]:= MapIndexed[(Evaluate[Symbol[#1]]=First[#2])&,a];

In[3]:= ?status
        Global`status
        status = 3

Or

In[4]:= Clear/@ a;    (* to repeat that, we first have to clear the symbols *)

In[5]:= MapThread[Set,{Symbol/@a , Range[Length[a]]}];

In[6]:= ?odag
        Global`odag
        odag = 4



The question as how to proceed when you want to change values, and you only have the names at hand, is not trivial but a FAQ, see the archive, if you are interested.

Good advice to you depends on what you really want to do. If you just want to associate your "names" with values you might better proceed differently (assoc here is the name of your association):

In[7]:= Thread[Evaluate[assoc /@ a] = Range[Length[a]]]
Out[7]= {1, 2, 3, 4}

This retrieves a "value":

In[8]:= assoc["gender"]
Out[8]= 2


This re-assigns a "value":

In[9]:= assoc["gender"] = 999
Out[9]= 999

--
Hartmut Wolf


  • Prev by Date: Re: Set working directory? Read polynomial from text file?
  • Next by Date: Re: Numerical Optimization involving equation solving
  • Previous by thread: Re: enumerating list items
  • Next by thread: Re: enumerating list items