30秒到达战场
根据 的文档,itertools.product该函数等价于以下 Python 代码:def product(*args, repeat=1): pools = [tuple(pool) for pool in args] * repeat result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod)由于格雷码产品是关于反转每个池的前一个序列的顺序,因此您可以在迭代它时使用enumerate上一个result列表来确定索引是奇数还是偶数,如果它是则反转池的序列奇数:def gray_code_product(*args, repeat=1): pools = [tuple(pool) for pool in args] * repeat result = [[]] for pool in pools: result = [x+[y] for i, x in enumerate(result) for y in ( reversed(pool) if i % 2 else pool)] for prod in result: yield tuple(prod)以便:for p in gray_code_product(['a','b','c'], [0,1], ['x','y']): print(p)输出:('a', 0, 'x')('a', 0, 'y')('a', 1, 'y')('a', 1, 'x')('b', 1, 'x')('b', 1, 'y')('b', 0, 'y')('b', 0, 'x')('c', 0, 'x')('c', 0, 'y')('c', 1, 'y')('c', 1, 'x')