问题描述
我有 N 号,我想制作大量数组。例如,我需要 N=2
(0,0),(0.5,0),(0,0.5),(1,1) ,(1,0.5), (0.5,1)
对于N=3
就像
(0,0,0),(0.5,0,0)...(0.5,0.5,0)....(1,0.5,0.5)...(1,1,1)
其中包含0, 0.5, 1
所有组合。
我尝试使用循环 for ,但没有找到解决问题的方法,任何 NI 更喜欢 python numpy
或 java,如果它是真的。
1楼
您可以使用生成所有组合。
def f(n):
return list(itertools.product((0, .5, 1), repeat=n))
print(f(2))
# [(0, 0), (0, 0.5), (0, 1), (0.5, 0), (0.5, 0.5), (0.5, 1), (1, 0), (1, 0.5), (1, 1)]
编辑:
如果您只想要相邻元素的组合,我们可以使用itertools
文档中的pairwise
配方。
from itertools import tee, chain, product
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def f(n):
values = (0, .5, 1)
return list(chain.from_iterable(product(x, repeat=n) for x in pairwise(values)))
print(f(n))
# [(0, 0), (0, 0.5), (0.5, 0), (0.5, 0.5), (0.5, 0.5), (0.5, 1), (1, 0.5), (1, 1)]