2011-07-19 69 views
5

這個Python代碼可以改進嗎?這個Python腳本可以改進嗎?

def build_list(types): 
     for x in types: 
      for a in ['short', 'long', 'average']: 
       for b in ['square', 'sloped', 'average']: 
        for c in ['small', 'large', 'average']: 
         for d in ['thin', 'thick', 'average']: 
          for e in ['high', 'low', 'average']: 
           for f in [True, False]: 
            for g in [True, False]: 
             for h in ['flat', 'thick', 'average']: 
              for i in ['long', 'short', 'average']: 
               for j in [True, False]: 
                for k in ['thin', 'thick', 'average']: 
                 for l in ['thin', 'thick', 'average']: 
                  yield [x, a, b, c, d, e, f, g, h, i, j, k, l] 
    facets_list = list(build_list(xrange(1,121))) 
    print len(facets_list) 
+6

,因爲我看到了,我的眼睛凸出,我心想,「是的!」 –

回答

12

是的。您可以儘快使用itertools.product()

import itertools 
facets_list = list(itertools.product(types, 
            ['short', 'long', 'average'], 
            ['square', 'sloped', 'average'], 
            ['small', 'large', 'average'], 
            ...)) 
+0

並使用'tuple's而不是'list's(使原始版本快12%左右)。 –

+0

謝謝gnibbler! – lxneng

+0

這個解決方案的速度大約是原始版本的兩倍,並且使用'tuple's而不是'list's使得它的速度更快1-2%(與原來的差別要小得多)。 –

相關問題