你可以编写一个返回函数的函数:
def cyclic_perm(a):
n = len(a)
b = [[a[i - j] for i in range(n)] for j in range(n)]
return b
def cyclic_perm_func(a):
n = len(a)
def wrapper(a, n, j):
def cyc():
return [a[i - j] for i in range(n)]
return cyc
b = [wrapper(a, n, j) for j in range(n)]
return b
a = [1, 2, 3, 4,5,6]
print(cyclic_perm(a))
f = cyclic_perm_func(a)
print([g() for g in f])
输出:
[[1, 2, 3, 4, 5, 6], [6, 1, 2, 3, 4, 5], [5, 6, 1, 2, 3, 4], [4, 5, 6, 1, 2, 3], [3, 4, 5, 6, 1, 2], [2, 3, 4, 5, 6, 1]]
[[1, 2, 3, 4, 5, 6], [6, 1, 2, 3, 4, 5], [5, 6, 1, 2, 3, 4], [4, 5, 6, 1, 2, 3], [3, 4, 5, 6, 1, 2], [2, 3, 4, 5, 6, 1]]
请注意,
wrapper()
是捕获每个实例中包装函数
cyc()
所需参数的方法。
itertools.permutations
而不是重新发明轮子。 - DeepSpace