irene
irene

Reputation: 2253

Declaring multiple variables using the same function in Python

Long-hand this is how it would look like:

class TestClass(object):
    def f(num):
        """In general, a complicated function."""
        return num

    self.a = f(1)
    self.b = f(2)
    self.c = f(3)
    self.d = f(4)
    self.e = f(5)

I'm thinking dictionary methods could help, but how?

Upvotes: 2

Views: 1231

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

As you said you better to use a dictionary.And as a more pythonic way you can use a dictionary comprehension.You can use enumerate to create a sequence of keys for your dictionary based on your items index. :

>>> my_dict = {'a{}'.format(i):f(j) for i,j in enumerate([3,4,5,1,2])}
{'a1': 4, 'a0': 3, 'a3': 1, 'a2': 5, 'a4': 2}

And for accessing to each value you can use a simple indexing :

>>> my_dict['a3']
1

Also if you want to use custom names for your keys you can use zip function to zip the variable names with values the use if within a dict comprehension:

>>> var_names=['a','b','c','d','e']
>>> values=[1,2,3,4,5]
>>> 
>>> my_dict = {i:f(j) for i,j in zip(var_names,values)}
>>> my_dict
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49330

You're going in the wrong direction - if you want to assign several references based on the same function, you should be storing them in a data structure like a list instead of in discrete, manually-entered variables. You can unpack them like that later if you want, but you should start with a data structure. It then becomes easier to map() each value in an iterable to this function, and then turn it into a list.

def f(num):
    """In general, a complicated function."""
    return num

my_numbers = list(map(f, range(1, 6)))

Your numbers were a tidy range this time so I just used a range() object, but you can use any iterable you like, such as [1, 2, 3] or (4, 2, 3).

Upvotes: 1

Related Questions