当前位置: 代码迷 >> python >> 用序列填充数组
  详细解决方案

用序列填充数组

热度:98   发布时间:2023-07-16 11:20:44.0

我有 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,如果它是真的。

您可以使用生成所有组合。

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)]
  相关解决方案