我是Python的新手,我写了一个函数:
def f(x, y, z): ret = [] for i in range(x): for j in range(y): for k in range(z): ret.append((i, j, k)) return ret print f(2, 3, 4)
输出:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]
但我对此并不满意,因为我认为必须缩短实施时间.
那么任何人都可以给我一些暗示吗?
您可以使用,itertools.product
因为这基本上就是您所追求的笛卡尔积
>>> from itertools import product >>> list(product(range(2), range(3), range(4))) [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]
因此,您可以替换现有的功能
def f(x, y, z): return list(product(range(x), range(y), range(z)))
要删除必须输入的次数range
,可以接受单个列表参数,然后使用生成器表达式,例如
def f(l): return list(product(*(range(i) for i in l)))
那么你可以称之为
>>> f([2,3,4]) [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]