例如,如果 function(2) 那么它会产生
['XX','XO','OX','OO']
我不确定我将如何解决这个问题
请您参考如下方法:
除非这是一项任务,否则请使用 product来自 itertools,像这样:
>>> import itertools as it
>>> list(it.product('XO', repeat=2))
[('X', 'X'), ('X', 'O'), ('O', 'X'), ('O', 'O')]
如果您想知道如何以“长”方式执行此操作,可以在文档中找到 product 方法的实现:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
