这个Python脚本可以改进吗?

lxn*_*eng 5 python yield

这个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)
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 12

是.您可以使用itertools.product()

import itertools
facets_list = list(itertools.product(types,
                                    ['short', 'long', 'average'],
                                    ['square', 'sloped', 'average'],
                                    ['small', 'large', 'average'],
                                     ...))
Run Code Online (Sandbox Code Playgroud)

  • 是的,它的初始化是开销.一般规则:元组在适当的情况下优于列表,除非您想要写入,否则应始终使用它们. (2认同)