开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜