lundi 14 août 2017

Pythonic way to use the second condition in list comprehensions

Let's assume the following function:

def myfun(my_list, n, par1=''):
    if par1 == '':
        new_list = [[my_fun2(i,j) for j in range(n)] for i in range(n)]
    else:
        new_list = [[my_fun2(i,j) for j in range(n)] for i in range(n) if my_fun2(i,n) == par1]
    return new_list

As you can see, there are two different scenarios depending on par1. I do not like that line 3 and line 5 are almost identical and do not follow the DRY principle. How can this code be improved?

Aucun commentaire:

Enregistrer un commentaire