How do I select the correct list based on the value of the argument?

I have a class that contains multiple lists, i.e .:

class my_class(object):
    def __init__(self, list_A, list_B, ..., list_Z):
        self.list_A = list_A
        (...)
        self.list_Z = list_Z

      

then I need a method that will add the item to one of the lists. What I've done now is something like a switch case from C:

def add_to_list(self, list_name, item):
    if list_name == 'A':
        self.list_A.append(item)
    elif list_name == 'B':
        self.list_B.append(item)
    (...) and so on

      

It is very ineffective and needs a lot of work if I want to change anything. Is there a way to make it shorter? I imagine something similar to string.format ():

self.list_{}.append(item) .format(list_name)

      

+3


source to share


3 answers


Do not create program logic around variable names. Please indicate the criteria by which one element should complete the complete list in order to sort it by a specific list. If its a simple alphabetical order, just express it in your code.

Example:



class my_class():
    def __init__(self):
        self.list_A = []
        self.list_B = []
        self.dict = { "A":self.list_A, "B":self.list_B }

    def add_to_list(self, key):
        # Logic in here
        self.dict.get(key[:1]).append(key)

if __name__ == "__main__":
    c = my_class()
    c.add_to_list("Apple")
    c.add_to_list("Bus")
    c.add_to_list("Airplane")
    print(c.dict["A"])
    print(c.dict["B"])

      

+4


source


Use getattr

to access the attribute



def append(self, list_name, item):
    getattr(self, 'list_%s' % list_name).append(item)

      

+2


source


you can do it with a dictionary.

class base:
    def __init__(self, * pack):
        self.dictitems={}
        for i, j in zip('abcdefg',pack):
            self.dictitems[i]=j


    def add(self,list_name,item,key):

        self.dictitems[key].append(item)

    def printdict(self):
        print(self.dictitems)

a,b,c =[ [] for i in range(3)]
z=base(a,b,c)
z.add(b, 5 ,key ='b')
z.add(b, 7 ,key ='b')
z.add(c, 7 ,key ='c')
z.printdict()

      

0


source







All Articles