Python 用序列填充数组

Python 用序列填充数组,python,arrays,list,sequence,Python,Arrays,List,Sequence,我有N个数,我想做大量的数组。例如,N=2 我需要 对于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的所有组合 我尝试使用cycle for,但没有找到解决任何N问题的方法。我更喜欢pythonnumpy或java(如果是真的)。您可以使用它来生成所有组合 def f(n): return list(itertools.product((0, .5, 1), repeat=n

我有N个数,我想做大量的数组。例如,N=2 我需要

对于
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
的所有组合

我尝试使用cycle for,但没有找到解决任何N问题的方法。我更喜欢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)]

似乎与Java无关。请删除[Java]标记。在开始键入代码之前,您应该先了解一些想法。很抱歉,这是单击错误,删除了。我想到了它,但OP的示例中没有
(0,1)
。OPs示例似乎只有相邻元素,我将尝试使用其他itertools工具,它们给出了组合类型。
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)]