我正在尝试生成一组{0,1}和{00,01,10,11}的所有可能的组合,它应该是一个形状为(16,4)的数组。
这样的事情
[[((0,0),0), ((0,1),0), ((1,0),0), ((1,1),0)],
[((0,0),0), ((0,1),0), ((1,0),0), ((1,1),1)],
...
[((0,0),1), ((0,1),1), ((1,0),1), ((1,1),1)],
...
]]
这实际上不需要数组,我滥用了数组这个词,因为list没有形状:)
'00‘很好,(0,0)更好,因为后者很好看,
注意:应该在外部列表中有16项,在内部列表中有4项
代码可以给出最小的块
bset = np.array([0,1])
fset = np.array(np.meshgrid(bset,bset)).T.reshape(-1,2)
[tuple(i) for i in fset]
这就是
[(0, 0), (0, 1), (1, 0), (1, 1)]
到目前为止,一切都很好,然后事情就变得一团糟了。
这段代码
np.array(np.meshgrid(t4,bset), np.object)
给出
array([[[0, 0, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 1, 1, 0, 1, 1]],
[[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1]]], dtype=object)
而不是像这样
[((0,0),0), ((0,1),0), ((1,0),0), ((1,1),0)]
我也尝试过迭代工具。
arr = [(0, 0), (0, 1), (1, 0), (1, 1)]
list(combinations(arr, 2))
是近的
[((0, 0), (0, 1)),
((0, 0), (1, 0)),
((0, 0), (1, 1)),
((0, 1), (1, 0)),
((0, 1), (1, 1)),
((1, 0), (1, 1))]
怎么解决这个问题?
发布于 2019-08-09 02:51:12
您可以通过以下方式使用itertools.product
:
>>> options = (0, 1)
>>> base = list(it.product(options, options))
>>> output = [list(zip(base, i)) for i in it.product(*[options]*4)]
>>> pprint(output)
[[((0, 0), 0), ((0, 1), 0), ((1, 0), 0), ((1, 1), 0)],
[((0, 0), 0), ((0, 1), 0), ((1, 0), 0), ((1, 1), 1)],
[((0, 0), 0), ((0, 1), 0), ((1, 0), 1), ((1, 1), 0)],
[((0, 0), 0), ((0, 1), 0), ((1, 0), 1), ((1, 1), 1)],
[((0, 0), 0), ((0, 1), 1), ((1, 0), 0), ((1, 1), 0)],
[((0, 0), 0), ((0, 1), 1), ((1, 0), 0), ((1, 1), 1)],
[((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)],
[((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 1)],
[((0, 0), 1), ((0, 1), 0), ((1, 0), 0), ((1, 1), 0)],
[((0, 0), 1), ((0, 1), 0), ((1, 0), 0), ((1, 1), 1)],
[((0, 0), 1), ((0, 1), 0), ((1, 0), 1), ((1, 1), 0)],
[((0, 0), 1), ((0, 1), 0), ((1, 0), 1), ((1, 1), 1)],
[((0, 0), 1), ((0, 1), 1), ((1, 0), 0), ((1, 1), 0)],
[((0, 0), 1), ((0, 1), 1), ((1, 0), 0), ((1, 1), 1)],
[((0, 0), 1), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)],
[((0, 0), 1), ((0, 1), 1), ((1, 0), 1), ((1, 1), 1)]]
发布于 2019-08-09 02:48:03
你可以实现这一点而不需要矮胖。假设您有两个这样的列表:
>>> l1 = ['0', '1']
>>> l2 = ['00','01','10','11'] # using string as your question is unclear, see below
您可以这样使用itertools.product
:
>>> import itertools
>>> result = list(itertools.product(l1, l2))
>>> result
[('0', '00'), ('0', '01'), ('0', '10'), ('0', '11'), ('1', '00'), ('1', '01'), ('1', '10'), ('1', '11')]
itertools.product
返回一个可迭代的。
在我们的问题中,您的输入集是{00,01,10,11}
,在输出中,您需要(0, 0),..
,这是一些错误吗?
您也可以在itertools.product
上执行set
,但是您在问题中提供的集合不是有效的python代码。
尽管你的问题还不清楚投入,但我假设它是:
set1 = {0, 1}
set2 = {(0, 0, ), (0, 1, ), (1, 0, ), (1, 1, )} # if you have a string or something else, convert it to tuple
然后你可以使用这样的东西:
import pprint
result = [list(itertools.product(set2, [x])) for x in set1]
pprint.pprint(result)
输出:
[[((0, 1), 0), ((1, 0), 0), ((0, 0), 0), ((1, 1), 0)],
[((0, 1), 1), ((1, 0), 1), ((0, 0), 1), ((1, 1), 1)]]
https://stackoverflow.com/questions/57428261
复制相似问题