i have class contains several 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 need method append element 1 of lists. did switch case 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) (...) , on
its uneffective, , needs lot of work if want change something. there way make shorter? imagine analogous string.format():
self.list_{}.append(item) .format(list_name)
don't build programs logic around variable names. please specify criteria 1 item has fullfill in order sorted particular list. if simple alphabetical order, express within 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"])
Comments
Post a Comment