List mapping question

Steven Bethard steven.bethard at gmail.com
Thu Feb 3 17:36:18 EST 2005


Marc Huffnagle wrote:
> Steve Holden wrote:
> 
>>  >>> a,b,c = 1.1, 2.2, 3.3
>>  >>> a,b,c = map(int, (a,b,c))
>>  >>> a,b,c
>> (1, 2, 3)
>>  >>> a,b,c = [int(x) for x in (a,b,c)]
>>  >>> a,b,c
>> (1, 2, 3)
>>
>> regards
>>  Steve
> 
> Thanks ... so there's no way to pass an actual variable into a list 
> mapping, instead of its value?  I guess I'm thinking of something the 
> equivalent of call by reference.

No, not really.  You could do something like:

py> a, b, c = 1.1, 2.2, 3.3
py> mod = __import__(__name__)
py> for name in ('a', 'b', 'c'):
...     setattr(mod, name, int(getattr(mod, name)))
...
py> a, b, c
(1, 2, 3)

where you use the namespace in which the name resides (the module), but 
I'd probably advise against it...  I would suggest doing something like:

py> myvars = dict(a=1.1, b=2.2, c=3.3)
py> for key, value in myvars.iteritems():
...     myvars[key] = int(value)
...
py> myvars
{'a': 1, 'c': 3, 'b': 2}

If you want to pass around variables, it's generally better to put them 
in a dict, list, class instance or some other sort of container then 
mess around with them at the module level...

(another) STeVe



More information about the Python-list mailing list