用序列填充数组

2024-04-25 10:00:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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的所有组合。你知道吗

我试着使用cycle for,但是没有找到解决问题的方法,我更喜欢pythonnumpy或者java(如果它是真的)。你知道吗


Tags: 方法for数组java解决问题cycle个数pythonnumpy
1条回答
网友
1楼 · 发布于 2024-04-25 10:00:09

可以使用^{}生成所有组合。你知道吗

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)]

相关问题 更多 >