开发者

Refactoring a python function so that it can take any sized list

开发者 https://www.devze.com 2023-02-18 17:34 出处:网络
How can I make this function take as input an arbitrary list size? def ugly_function(lst): for a in lst[0]:

How can I make this function take as input an arbitrary list size?

def ugly_function(lst):
    for a in lst[0]:
        for b in lst[1]:
            for c in lst[2]:
                for d in lst[3]:
           开发者_开发问答         for e in lst[4]:
                        for f in lst[5]:
                            for g in lst[6]:
                                for h in lst[7]:
                                    if some_test([a,b,c,d,e,f,g,h]): 
                                        return [a,b,c,d,e,f,g,h]


Check out itertools.

def ugly_function(lst):
   for comb in itertools.product(*lst):
      if some_test(comb):
          return comb

(Or, as a 1-liner:

def ugly_function(lst):
    return next(comb for comb in itertools.product(*lst) if some_test(comb))


from itertools import ifilter, product

def nice_function(lst):
    return ifilter(some_test, product(*lst)).next()
0

精彩评论

暂无评论...
验证码 换一张
取 消